Python returns MagicMock object instead of return_value

When you @mock.patch('a.A'), you are replacing the class A in the code under test with mock_a.

In B.method_b you then set a = A(), which is now a = mock_a() – i.e. a is the return_value of mock_a. As you haven’t specified this value, it’s a regular MagicMock; this isn’t configured either, so you get the default response (yet another MagicMock) when calling methods on it.

Instead, you want to configure the return_value of mock_a to have the appropriate method, which you can do as either:

mock_a().method_a.return_value="Mocked A" 
    # ^ note parentheses

or, perhaps more explicitly:

mock_a.return_value.method_a.return_value="Mocked A"

Your code would have worked in the case a = A (assigning the class, not creating an instance), as then a.method_a() would have triggered your mock method.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)