|
Testing Patterns for Java Unit Tests
Identify common patterns in test cases, and use them to create new tests
by Mirko Raner
July 13, 2005
In 1995 the famous Gang of Four—Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides—introduced the concept of design patterns for software development. Design patterns increase development efficiency by helping developers identify common problems and apply standard solutions to these problems. Most developers use design patterns for writing application code, but few realize that design patterns are also helpful for writing test cases. Let's explore how to identify common patterns in test cases and use these patterns to create new tests.
Patterns for JUnit Tests
Today, writing unit tests is an obligatory part of the software development process for most developers. For Java developers, unit testing means producing a JUnit test class for every class. If you are not fortunate enough to have access to sophisticated test-generation software, writing unit tests is probably a normal part of your day.
If you think that writing unit tests is often tedious, unrewarding, and even boring, you are not alone. Most developers would rather write code "that does something." Designing meaningful unit tests after you have written a class can take considerable time (unless you are using Test-Driven Design [TDD]). Moreover, writing unit tests is often a routine process that lends itself to mechanization. If you watch yourself closely while writing unit tests, you will notice that you very often apply a recurring pattern to create the unit test for a particular class. For example, one of the simplest and most familiar testing patterns consists of an invocation of a tested method on some test input, followed by an assertion of the corresponding expected output:
import junit.framework.*;
public class StringBufferTest
extends TestCase
{
public void testAppend() throws
Throwable
{
StringBuffer testObject =
new StringBuffer("a");
testObject.append("b");
assertEquals("ab",
testObject.toString());
}
}
Back to top
|