【发布时间】: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/…