Especially, the Mock Object Library is amazing! But, it’s -in some aspects- so different, compared to the other libraries I used before, that I took some time to write a Gist to help me and others better understand how it works.
You’ll find in the Gist below, different test classes for each different functionality/possibility:
* TestSimple. Uses “non-defined” methods from a MagicMock instance. As you can see, there’s no need to use a specification/interface, as you would need for Mockito.
* TestReturnValue. Uses the return_value field for returning custom values when treating the mock as a function or class method. You can also capture how many times the mock has been called and the parameters passed to it.
* TestSideEffect. Uses the side_effect field for defining a function that would be used when executing the mock as a function or class method. You can use this function for raising exceptions or just executing some logic before returning.
* TestSpec. Uses the spec and spec_set fields for defining an object or class that would be used as the blueprint/interface of the resulting mock. This is similar to how Mockito works. One field (spec) allows you to expand the interface, but the other (spec_set) not.
* TestWraps. Uses the wraps field for defining an object or class that would be wrapped with a MagicMock instance. The original object behavior would be there, but you can expand it!
* TestPatch. Uses the patch function for changing the behavior of external functions and/or classes. This is fundamental when you need to change collaborators behavior, specially when these are not part of your codebase.
Thanks for reading!
Read behind a paywall here.