Reputation: 13
I am trying to unit test a module (using pytest and pytest-mock) and I would like to create a mocked instance of a class with certain values for its attributes to be used in a @pytest.fixture
I think I've finally found what I'm looking for in patch.object and autospeccing but I don't understand what the arguments are supposed to be, specifically 'attribute'
patch.object(target, attribute, new=DEFAULT, spec=None, create=False,
spec_set=None, autospec=None, new_callable=None, **kwargs)
patch the named member (attribute) on an object (target) with a mock object.
I tried searching for patch.object() examples but I'm only seeing use cases related to mocking the return values for methods in a class.
Like in this example, a method is passed as the 'attribute' argument to patch.object().
Any help or hints in the right direction would be greatly appreciated!
Upvotes: 1
Views: 1158
Reputation: 1355
An example would be the method that you're trying to test.
So, if I wanted to check to see if MyClass.method_a
was called, I would do:
from .functions import MyClass # import MyClass from wherever
# it is used in the module.
with patch.object(MyClass, 'method_a') as mocked_myclass:
function_that_called_myclass_method_a()
mocked_myclass.assert_called()
Upvotes: 1