【问题标题】:mock out methods of base class模拟出基类的方法
【发布时间】:2015-08-04 18:56:47
【问题描述】:

如何模拟基类来测试派生类的其余行为?

# themod/sql.py

class PostgresStore(object):
    def __init__(self, host, port):
        self.host = host
        self.port = port

    def connect(self):
        self._conn = "%s:%s" % (self.host, self.port)
        return self._conn


# themod/repository.py
from .sql import PostgresStore


class Repository(PostgresStore):

    def freak_count(self):
        pass


# tests/test.py
from themod.repository import Repository
from mock import patch 

@patch('themod.repository.PostgresStore', autospec=True)
def patched(thepatch):
    # print(thepatch)
    x = Repository('a', 'b')

    #### how to mock the call to x.connect?
    print(x.connect())

patched()

【问题讨论】:

  • 你不能,除非重建子类。子类保留对基类的引用,而您没有修补该引用
  • 直接在子类上模拟出继承的方法。
  • @MartijnPieters 如果我也打算测试子类,那不是目的吗?
  • @AnuvratParasha 所以第一件事是你应该存根交互点。因此,即使您能做到这一点,它也不是做事的理想方式。 stackoverflow.com/questions/1595166/…

标签: python testing mocking


【解决方案1】:

您不能像这样模拟 Class。您应该模拟出其中的一个功能。试试:

with patch.object(PostgresStore, 'connect', return_value=None) as connect_mock:
  # do something here
  assert connect_mock.called

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-30
    • 2019-07-05
    • 1970-01-01
    • 2022-11-30
    相关资源
    最近更新 更多