Mocking in Python with unittest.mock allows you to simulate complex logic or unpredictable dependencies, such as responses from external services, in a testing environment. A mock object is a substitute object that simulates a real object in a testing environment, enabling controlled and predictable test environments for your Python code. The Mock class allows you to imitate real objects, and the patch() function lets you temporarily substitute mocks for real objects in your tests. Mock differs from MagicMock in that MagicMock includes implementations of most magic methods. You can assert if a Mock object was called with methods like .assert_called() and set a mock's return value by assigning a value to the mock's .return_value attribute. Using mock objects is a versatile and powerful way to improve the quality of your tests, especially when testing areas of your codebase that are hard to satisfy, such as except blocks and if statements. The Python mock object library, unittest.mock, provides an easy way to introduce mocks into your tests and is included in the standard library starting from Python 3.3. The library offers a class called Mock, which you'll use to imitate real objects in your codebase, and a function called patch(), which replaces the real objects in your code with Mock instances. By using Python mock objects, you can control your code's behavior during testing and understand how you're using their real counterparts in your code. Mock objects contain data about their usage that you can inspect, such as if you called a method, how you called the method, and how often you called the method.
realpython.com
realpython.com
