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 class.
The unittest.mock.Mock class is the core of the Python mocking framework. All we need to do is to instantiate the class and pass it in where it is required. The mock will record if it was...