Python 基类的模拟方法
如何模拟基类来测试派生类的其余行为Python 基类的模拟方法,python,testing,mocking,Python,Testing,Mocking,如何模拟基类来测试派生类的其余行为 # 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._c
# 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()
你不能模仿
类
。您应该模拟其中的一个函数。尝试:
with patch.object(PostgresStore, 'connect', return_value=None) as connect_mock:
# do something here
assert connect_mock.called
如果不重建子类,就不能。子类保留了对基类的引用,而您没有修补该引用。取而代之的是直接在子类上模拟继承的方法。@MartijnPieters如果我也打算测试该子类,它会超出目的,不是吗?@AnuvratParashar所以第一件事是您应该存根交互点。因此,即使你能做到这一点,这也不是理想的做事方式。