我有这样的事情:

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

最佳答案

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

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

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

关于python - 模拟作为参数传递的类,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43835012/

10-09 06:38