'Setup mock without changing `called` count

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?



Solution 1:[1]

Dumb me... It was enough to use MyClass.return_value.my_method.return_value = 'foo' instead of MyClass().my_method.return_value = 'foo'

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Vito De Tullio