Review
In this chapter, we looked at how to test a layer of code in isolation using mocks and mock objects. Mocks allow us to swap out pieces of the application code with mock objects or other code. In addition:
-
Mock objects can simulate return values, raise exceptions, and record how they were called.
-
Using autospec=True when mocking objects, such as CardsDB, can help avoid mock drift and make sure our use of the mock in tests is the same as the API of the object being mocked.
-
Return values can be simulated with mock_object.return_value = <new value>.
-
Exceptions can be simulated with mock_object.side_effect = Exception.
Mock objects return new mock objects when called as a function, unless you’ve set their return_value.
Mocking has some drawbacks, ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access