在Python中,如果测试代码可以访问模拟对象,那么如何从中获取构建它时测试中的代码所传递的参数?
以下是我尝试做的一个简单示例。 TODO标志着我不知道如何按预期正确行事。
from unittest import mock
# Under test:
class Foo(object):
def __init__(self, x):
self._x = x
def compute():
return hash(self._x)
def computeFoo():
return Foo("abc").compute() + Foo("def").compute()
# Test:
class MockFoo(mock.MagicMock):
def compute(self):
# TODO: How to get the value x which was passed to the Foo constructor?
if self._x == "abc":
return 0
return 1
if __name__ == "__main__":
m = MockFoo()
mock.patch(__name__ + ".Foo", return_value=m).start()
assert computeFoo() == 1
感谢您的帮助。