Event Listener Testing

Problem

You want to create a mock implementation of an event listener interface.

Solution

Write a class that implements the interface, but only define behavior for the methods you need for your current test.

Discussion

Java Swing user interfaces rely heavily on models and views. In the case of tables, for instance, the TableModel interface is the model and JTable is one possible view. The table model communicates with its view(s) by sending TableModelEvents whenever its data changes. Since numerous views may observe a single model, it is imperative that the model only sends the minimum number of events. Poorly written models commonly send too many events, often causing severe performance problems.

Let’s look at how we can use mock objects to test the events fired by a custom table model. Our table model displays a collection of Account objects. A mock table model listener verifies that the correct event is delivered whenever a new account is added to the model. We’ll start with the Account class, as shown in Example 6-1.

Example 6-1. The Account class

package com.oreilly.mock; public class Account { public static final int CHECKING = 0; public static final int SAVINGS = 1; private int acctType; private String acctNumber; private double balance; public Account(int acctType, String acctNumber, double balance) { this.acctType = acctType; this.acctNumber = acctNumber; this.balance = balance; } public int getAccountType( ) { return this.acctType; } public String ...

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.