我有一个实例方法,它启动另一个类的对象。例如,
import module_two
class One:
def start(self):
self.two = module_two.Two()
我正在修补我的测试用例中的一个类
@patch('module_one.One', autospec=True)
def test_one(patched_one):
two = patched_one.return_value
# Following method should raise error, but doesn't
two.any_random_non_existing_method()
如前所述,two.any_random_non_existing_method() 不会引发任何错误,因为 two Mock 对象没有分配任何规范。
如何将 spec 分配给 two 对象。?我正在寻找类似以下片段的内容。
# note: configure_spec actually doesn't exist.!
two.configure_spec(module_two.Two)
two.any_random_non_existing_method() # Error.!
请您参考如下方法:
经过一些评论,看起来 mock_add_spec 对你有用:
Add a spec to a mock. spec can either be an object or a list of strings. Only attributes on the spec can be fetched as attributes from the mock.
https://docs.python.org/3/library/unittest.mock.html#unittest.mock.Mock.mock_add_spec
它应该是这样的:
# Add specifications on existing mock object
two.mock_add_spec(module_two.Two)
two.any_random_non_existing_method() # Error.!
