Mock Object Self-Validation

Problem

You want to avoid duplicated validation logic in your tests.

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.

Example 6-5. Improved unit test

public void testAddAccountEvent(  ) {
    MockTableModelListener mockListener = new MockTableModelListener(  );
    mockListener.setExpectedEventCount(1);
    TableModelEvent evt = new TableModelEvent(
            this.acctTableModel,
            this.accounts.length,
            this.accounts.length,
            TableModelEvent.ALL_COLUMNS,
            TableModelEvent.INSERT);
    mockListener.addExpectedEvent(evt);

    this.acctTableModel.addTableModelListener(mockListener);

    this.acctTableModel.addAccount(new Account(
            Account.CHECKING, "12345", 100.50));

    mockListener.verify(  );
}

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 ...

Get Java Extreme Programming Cookbook 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.