基础方法的模拟 class
mock out methods of base class
如何模拟基 class 以测试派生 class 的其余行为?
# 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()
你不能这样模拟 Class
。您应该模拟其中的一个功能。尝试:
with patch.object(PostgresStore, 'connect', return_value=None) as connect_mock:
# do something here
assert connect_mock.called
如何模拟基 class 以测试派生 class 的其余行为?
# 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()
你不能这样模拟 Class
。您应该模拟其中的一个功能。尝试:
with patch.object(PostgresStore, 'connect', return_value=None) as connect_mock:
# do something here
assert connect_mock.called