最简单的事情就是从一个例子开始......
要测试的示例代码:
type1_instance1 = f1()
type1_instance2 = f2()
compareResult = type1_instance1 < type1_intstance2
if compareResult:
print(type1_instance1.generate_value())
实例 1 和 2 是一些自定义类的实例。
在测试时 f1 和 f2 被模拟以返回 MagicMocks。这样就可以对这些返回值调用自定义类的方法。
执行比较代码时出现错误
'<' not supported between instances of 'MagicMock' and '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
请您参考如下方法:
您应该改写 MagicMock 对象的 __lt__ 属性的 return_value 属性,并使用 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
