0

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?

1 Answer 1

1

The mock has to account for the instantiation some_class() as well:

MockSomeClass.return_value.my_method.return_value = 'Some useful answer' internal = some_class() internal.my_method() # 'Some useful answer 
Sign up to request clarification or add additional context in comments.

1 Comment

It worked like a charm. Just to complete the answer, the assertion must be done like MockSomeClass.return_value.my_method.assert_called_once(). Thank you!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.