我正在尝试在 Python 3 中测试 ClassToTest
:
from path.to import ClassThatNeedsMocking
class ClassToTest:
def __init__(self):
pass
def setup(self):
foo = ClassThatNeedsMocking()
foo.functionCall()
这个类是由其他一些类实现的,所以我做了一个简单的设置:
from some.other.path import ClassToTest
class ImplementingClass(ClassToTest):
def __init__(self):
super().__init__()
我想使用以下内容模拟 ClassToTest
中的 functionCall
:
class TestClass:
def testMethod(self):
patch = mock.patch('path.to.ClassThatNeedsMocking')
patcher = patch.start()
patcher = MagicMock()
patcher.functionCall = MagicMock()
foo = ImplementingClass()
foo.setup()
# Results in an 'Expected to have been called once. Called 0 times.'
patcher.functionCall.assert_called_once()
patch.stop()
当在 ClassToTest
中打印 foo.functionCall()
时,它返回一个 MagicMock
对象,但断言仍然失败。这是正确的测试设置吗?我在这里缺少什么?
最佳答案
这才是有效的:
@mock.patch('path_to_class_to_test.ClassThatNeedsMocking')
def test_method(patched):
foo = ImplementingClass()
foo.setup()
patched.return_value.functionCall.assert_called_once()
首先,您需要在要测试的类中修补导入的类(请参阅 where to patch )。如果使用 import from ,该类将被分配给一个新对象,该对象位于 using 模块中,并且这是必须修补的对象。
其次,您只需要修补的类 - 不需要另一个模拟,或启动/停止修补程序。您可以使用装饰器(就像我所做的那样)或函数调用来获取它。一旦超出函数范围,修补就会恢复。
第三,您修补了该类,但该函数是由类实例调用的,即patched.return_value
,因此您必须检查这一点。
关于python - 名为断言的函数在模拟导入类上失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61522439/