ability to change behavior of an object in the context of a test without affecting other tests that use the same object. • Test flexibility • Its easy!!!
my_mock_object.attr_x = 3 • Treat it like a method and add a return value. – >>> my_mock_object.return_value = 42 – >>> my_mock_object() – ... 42 • Monkey patch a method on a class we're testing. (extending on example above) – >>> class RealDeal(object): – ... def a_func(): – ... return “a_func was called” – >>> real = RealDeal() – >>> real.a_func = my_mock_object – >>> real.a_func() – ... 42
in your code under test. • Access the mock that replaces the class by using the mock's return value. You can configure the mocked class however you need to from here. • Can be used in with statements or as a decorator on a test case or test class. As a decorator it comes in 3 flavors: – @patch – @patch.object – @patch.dict
MagicMock vs Mock. – Pretty much the same thing, except that MagicMock has magic functions already built onto the mock. • Create a mock from an existing class.