最简单的事情是从一个例子开始...
要测试的示例代码:
type1_instance1 = f1()
type1_instance2 = f2()
compareResult = type1_instance1 < type1_intstance2
if compareResult:
print(type1_instance1.generate_value())
实例1和2是某些自定义类的实例。
在测试中,将模拟
f1
和f2
以返回MagicMocks。这样就可以在这些返回值上调用自定义类的方法。当执行比较代码时,出现错误
“ MagicMock”和“ MagicMock”的实例之间不支持“
使MagicMocks与过载的运算符一起工作的最佳方法是什么?
这是我的解决方案:
def __lt__(self, other):
return mock.MagicMock
compareable_MagicMock_Instance = MagicMock()
setattr(compareable_MagicMock_Instance, '__lt__', __lt__)
f1.return_value = compareable_MagicMock_Instance
f2.return_value = another_compareable_MagicMock_Instance
最佳答案
您应该改写return_value
对象的__lt__
属性的MagicMock
属性,并使用patch
使f1
和f2
返回自定义的MagicMock
实例:
from unittest.mock import patch, MagicMock
def f1():
pass
def f2():
pass
compareable_MagicMock_Instance = MagicMock()
compareable_MagicMock_Instance.__lt__.return_value = True
with patch('__main__.f1', return_value=compareable_MagicMock_Instance), patch('__main__.f2', return_value=compareable_MagicMock_Instance):
type1_instance1 = f1()
type1_instance2 = f2()
compareResult = type1_instance1 < type1_instance2
if compareResult:
print('type1_instance1 is less than type1_instance2')
输出:
type1_instance1 is less than type1_instance2
关于python - Python3单元测试:如何使用运算符与MagicMocks进行比较,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55421771/