Skip to content
Advertisement

How to define a mock object inside a mock in python?

I have a class that contains another class in a variable. Now I want to write a unit-test and define a mock object. Therefore I define a fixture in conftest.py and monkeypatch it with the mock object. I now get a the desired mock object but the inner object is noch the mock object which I defined. The problem ist that my mock that I have created in the fixture (so that the mock returns “Bye”) will not be applied. How can I fix this and is there any better solution? See my minimal example below:

module_a.py

JavaScript

utils.py

JavaScript

module_main.py

JavaScript

conftest.py

JavaScript

test_module_main.py

JavaScript

Advertisement

Answer

Found a solution myself. When a new object is created (Util()) __call__ is triggered and returns a new object of the mock, hence all defined properties are lost. We just need to return the mock object itself with util_mock.return_value = util_mock.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement