4.16 Writing a Base Class for Your Tests
4.16.1 Problem
You want to reuse the same behavior in
all of your tests without duplicating code.
4.16.2 Solution
Define common behavior in a subclass of
junit.framework.TestCase and extend from your
class, rather than directly extending TestCase.
4.16.3 Discussion
JUnit does not require that your tests directly extend
TestCase. Instead, you can introduce new
TestCase extensions for common behavior. You
might want to ensure that some common initialization code is always
executed before each of your tests. In that case, you might write
something like this:
public abstract class MyAbstractTestCase extends TestCase {
public MyAbstractTestCase( ) {
initializeApplicationProperties( );
}
public MyAbstractTestCase(String testName) {
super(testName);
initializeApplicationProperties( );
}
// initialize some custom application framework. Leave this method
// protected so subclasses can customize.
protected void initializeApplicationProperties( ) {
MyFramework.initialize("common/myappconfig.properties");
}
}
Tests in your application can now extend
MyAbstractTestCase and your framework
initialization code will always be executed before the tests run.
Providing convenience methods is another reason why you might want to
extend TestCase. We show this in the next recipe
when we define a method to retrieve a Swing JFrame
for graphical testing.
|