我有这样的事情:
class ThisClass:
def my_method(self, param):
# Do normal stuff
pass
class OtherClass:
def my_method(self, param):
# Do crazy stuff
pass
def useful_function(some_class, some_param):
internal = some_class()
result = internal.my_method(some_param)
uses_result(result)
# The useful_function can be called with any of the classes
useful_function(ThisClass, 10)
我想要做的是测试my_method
内是否调用了useful_function
。我试图模拟类及其方法,但它不起作用:
# Inside the test class
def test_case(self):
MockSomeClass = mock.Mock()
MockSomeClass.my_method.return_value = 'Some useful answer'
useful_function(MockSomeClass, 100)
MockSomeClass.my_method.assert_called_once()
错误依赖于我在my_method
中使用uses_result
的结果的事实,但模拟方法未按预期返回'Some useful answer'
。我做错了什么?
答案 0 :(得分:1)
模拟必须考虑实例化some_class()
:
MockSomeClass.return_value.my_method.return_value = 'Some useful answer'
internal = some_class()
internal.my_method() # 'Some useful answer