dimanche 7 mai 2017

Mocking a class passed as argument

I have something like this:

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)

What I want to do is to test if my_method was called inside useful_function. I tried to mock the class and its method, but it did not work:

# 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()

The error relies on the fact I use the result of my_method in uses_result, but the mocked method do not return 'Some useful answer' as expected. What am I doing wrong?

Aucun commentaire:

Enregistrer un commentaire