let's say I want to test this function
def my_function():
my_obj = MyClass()
return my_obj.my_method()
I want to mock MyClass
, so I use unittest.mock.patch
@patch('...MyClass')
def test_my_function(MyClass):
MyClass().my_method.return_value = 'foo'
assert my_function() == 'foo'
MyClass.assert_called_once()
this test fails at the last line with the error AssertionError: Expected 'MyClass' to have been called once. Called 2 times.
; witch, in a sense, is right: the first time is test_my_function
, when I set up the MyClass().my_method
return value.
What I want to express, however, is the fact that MyClass()
should be instantiated just once in my_function
.
Is there a way to "prepare" the nested mocks (so to set the return_value = 'foo'
) without changing the intermediate mocks "called" count?