模拟作为参数传递的类

时间:2017-05-07 18:15:26

标签: python unit-testing testing mocking

我有这样的事情:

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'。我做错了什么?

1 个答案:

答案 0 :(得分:1)

模拟必须考虑实例化some_class()

MockSomeClass.return_value.my_method.return_value = 'Some useful answer'

internal = some_class()
internal.my_method() # 'Some useful answer