Mock Object Self-Validation

Problem

Solution

Put the validation logic inside of the mock object. This way, every test that
uses the mock object will reuse the validation logic automatically.

Discussion

The code in the previous recipe showed how to create a mock table model
listener that kept track of a list of events. As you write more tests using this
mock object, you will find that your tests have to repeatedly check the number
of events as well as every field within the event objects. Rather than repeating
this logic in each of your tests, move some of the validation logic into the
mock object. Example 6-5 shows how this step simplifies your tests.

The modified unit test begins by setting the expected event count on the
improved mock object. The mock object will fail the test as soon as it receives
too many events. This is useful because it lets you see test failures as soon as
the extra events are delivered, making diagnosis easier.

The test also registers a specific expected event. Once the account is added
to the table model, the test calls verify( ), which tests against the
expected event. Example 6-6 shows the new, improved mock object.

As you can see, the mock object is significantly more complex in this
approach. Only write sophisticated mock objects when you find yourself using
them in a lot of different tests. As is customary in an XP approach, start
simple and then refactor the tests and mock objects as you observe duplicated
code.

Our mock object illustrates an interesting point about JUnit. The methods in
the junit.framework.Assert class are static, so we can call them from
our mock object, which is not itself a unit test: