O'Reilly logo

Java Extreme Programming Cookbook by Brian M. Coyner, Eric M. Burke

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required