Overview of the pMock API

Creating mocks

A mock object is created to represent a real object for the purposes of a unit test. Using a mock object rather than the real object can be useful if the real object is difficult to construct, hasn't been written yet or causes awkward side effects in use.

import pmock
...
mock = pmock.Mock()

Expectations are defined for the methods that are meant to be called on the mock object.

mock.expects(pmock.once()).render()

The mock can now be called with the expected method.

mock.render()

Calling the mock with unexpected methods causes an exception to be raised.

When the mock objects have been set up, they are then used in the unit test as the real objects would have been.

pictures = [mock]
gallery = Gallery(pictures)
gallery.render()

After the test's normal assertions have been made, an assertion that the mock's expectations have been satisfied should be made.

mock.verify()

If any of the mock's expectations haven't been satisfied, such as an expected method not having been called, then the verify call raises an exception.

Argument expectations

Expectations can be set on the arguments passed to the mock's methods.

mock.expects(pmock.once()).render(pmock.eq(640), pmock.eq(480))

The arguments to the expectation's mocked method are constraint objects which are evaluated on the actual arguments when a call is made to the mock object. If an argument doesn't satisfy its constraint then the expectation remains unsatisfied.

mock.expects(pmock.once()).render(brush=pmock.same(print.BIG_BRUSH))

More flexible argument constraints can be defined using a slightly more verbose set of methods.

Test base class

The MockTestCase class is a convenience base class for tests. It provides the mock method for creating mock objects that will be automatically verified after the test method has run. The verify calls are made to the mock object after tearDown has been called.