我有一个类似的测试
import somemodule
import somemodule2
class SomeTestCase(unittest.TestCase):
def setUp(self):
super().setUp()
self.ft_mock = mock.MagicMock(spec=somemodule.SomeClass,
name='mock_it')
def tearDown(self) -> None:
self.ft_mock.reset_mock(return_value=True, side_effect=True)
@mock.patch('somemodule2.someFunk2',
name = 'mock_2',
spec=True,
side_effect='some val')
def testSomething(self, mock_rr):
m = self.ft_mock
m.addMemberSomething()
self.assertEqual(len(m.addMember.call_args_list), 1)
m.addSomethingElse.return_value = 'RETURN IT'
m.addSomethingElse()
m.addSomethingElse.assert_called_once()
res = somemodule.FooClass.foo()
mock_rr.assert_called()
这里somemodule.FooClass.foo()
从someFunk2
内部调用somemodule2
,后者被模拟为mock_rr
在测试调试中,它确实会调用它,因为我从someFunk2
中打印出一行,但是在调用mock_rr.assert_called()
时对其进行了测试,它会抛出:
AssertionError: Expected 'mock_2' to have been called.
我已经尝试过使用patch和patch.object的几种方式
答案 0 :(得分:0)
问题是somemodule
也从someFunk2
导入了somemodule2
。
因此,在修补/模拟时,修补的对象来自somemodule2,而需要修补的 对象是somemodule.someFunk2