Using the Python mocking framework

The unittest.mock module provided by Python is an extremely powerful mocking framework, yet at the same time it is very easy to use.

Let us redo our tests using this library. First, we need to import the mock module at the top of our file as follows:

from unittest import mock

Next, we rewrite our first test as follows:

class EventTest(unittest.TestCase):
    def test_a_listener_is_notified_when_an_event_is_raised(self):
        listener = mock.Mock()
        event = Event()
        event.connect(listener)
        event.fire()
        self.assertTrue(listener.called)

The only change that we've made is to replace our own custom Mock class with the mock.Mock class provided by Python. That is it. With that single line change, our test is now using the inbuilt mocking ...

Get Test-Driven Python Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.