MagicMock. MagicMock objects provide a simple mocking interface that allows you to set the return value or other behavior of the function or object creation call that you patched. This allows you to fully define the behavior of the call and avoid creating real objects, which can be onerous.
With Mock you can mock magic methods but you have to define them. MagicMock has "default implementations of most of the magic methods.". If you don't need to test any magic methods, Mock is adequate and doesn't bring a lot of extraneous things into your tests.
I think the better way is to mock the property as PropertyMock , rather than to mock the __get__ method directly. It is stated in the documentation, search for unittest. mock. PropertyMock : A mock intended to be used as a property, or other descriptor, on a class.
mock documentation: spec: This can be either a list of strings or an existing object (a class or instance) that acts as the specification for the mock object. If you pass in an object then a list of strings is formed by calling dir on the object (excluding unsupported magic attributes and methods).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With