我正在测试这段代码:
def to_be_tested(x):
return round((x.a + x.b).c())
在我的单元测试中,我想断言这正是通过传递x
并返回结果来完成的,所以我将一个MagicMock
对象传递为x
:
class Test_X(unittest.TestCase):
def test_x(self):
m = unittest.mock.MagicMock()
r = to_be_tested(m)
然后我检查结果是否符合我的预期:
self.assertEqual(r._mock_new_name, '()') # created by calling
round_call = r._mock_new_parent
self.assertEqual(round_call._mock_new_name, '__round__')
c_result = round_call._mock_new_parent
self.assertEqual(c_result._mock_new_name, '()') # created by calling
c_call = c_result._mock_new_parent
self.assertEqual(c_call._mock_new_name, 'c')
add_result = c_call._mock_new_parent
self.assertEqual(add_result._mock_new_name, '()') # created by calling
add_call = add_result._mock_new_parent
self.assertEqual(add_call._mock_new_name, '__add__')
a_attribute = add_call._mock_new_parent
b_attribute = add_call.call_args[0][0]
self.assertEqual(a_attribute._mock_new_name, 'a')
self.assertEqual(b_attribute._mock_new_name, 'b')
self.assertIs(a_attribute._mock_new_parent, m)
self.assertIs(b_attribute._mock_new_parent, m)
导入后unittest.mock
,我需要修补mock
模块的内部结构,以便能够正确地对round()
函数进行魔术模拟(有关详细信息,请参阅https://stackoverflow.com/a/50329607/1281485):
unittest.mock._all_magics.add('__round__')
unittest.mock._magics.add('__round__')
所以,现在,正如我所说,这行得通。但我觉得它非常难以阅读。此外,我需要花很多时间才能找到诸如此类的东西_mock_new_parent
。下划线还表示这是一个“私有”属性,不应该使用。文档没有提到它。它也没有提到实现我尝试的另一种方法。
是否有更好的方法来测试返回MagicMock
的对象是否按照应有的方式创建?