From the documentation http://www.voidspace.org.uk/python/mock/patch.html
patch(target, new=DEFAULT, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs)
If new is omitted, then the target is replaced with a MagicMock. If patch is used as a decorator and new is omitted, the created mock is passed in as an extra argument to the decorated function. If patch is used as a context manager the created mock is returned by the context manager.
new_callable allows you to specify a different class, or callable object, that will be called to create the new object. By default MagicMock is used.
I am trying to understand the differences between the two, and what situation to use new_callable
instead of new
Patching vs Mocking: Patching a function is adjusting it's functionality. In the context of unit testing we patch a dependency away; so we replace the dependency. Mocking is imitating. Usually we patch a function to use a mock we control instead of a dependency we don't control.
Mock vs. So what is the difference between them? MagicMock is a subclass of Mock . It contains all magic methods pre-created and ready to use (e.g. __str__ , __len__ , etc.). Therefore, you should use MagicMock when you need magic methods, and Mock if you don't need 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. If you need to test a lot of magic methods MagicMock will save you some time.
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.
new
is an actual object; new_callable
is a callable used to create an object. The two cannot be used together (you either specify the replacement or a function to create the replacement; it's an error to use both.)
>>> foo = 6 >>> with mock.patch('__main__.foo', new=7): ... print foo ... 7 >>> with mock.patch('__main__.foo', new_callable=lambda : 8): ... print foo ... 8
When new
is mock.DEFAULT
, the mock object is a MagicMock
instance precisely because the default value of new_callable
is MagicMock
.
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