This post originated from an RSS feed registered with Agile Buzz
by Joe Walnes.
Original Post: JUnit tip: Setting the default timezone with a TestDecorator
Feed Title: Joe's New Jelly
Feed URL: http://joe.truemesh.com/blog/index.rdf
Feed Description: The musings of a ThoughtWorker obsessed with Agile, XP, maintainability, Java, .NET, Ruby and OpenSource. Mmm'kay?
A problem I was finding when testing XStream is that many of the tests were timezone dependent. Initially I had some code in each setUp()/tearDown() method to set the default timezone and reset it afterwards.
This lead to a lot of duplication. Putting the common code in a super class was an option but this lead to a fragile base class.
Using composition allows this commonality to be put in one case and applied to the relevant test cases. This gets out of the 'single inheritance' issue.
JUnit provides an (often overlooked) decorator class to help with this. Here's my TimeZoneTestSuite:
public class TimeZoneTestSuite extends TestDecorator {
private final TimeZone timeZone;
private final TimeZone originalTimeZone;
public TimeZoneTestSuite(String timeZone, Test test) {
super(test);
this.timeZone = TimeZone.getTimeZone(timeZone);
this.originalTimeZone = TimeZone.getDefault();
}
public void run(TestResult testResult) {
try {
TimeZone.setDefault(timeZone);
super.run(testResult);
} finally {
TimeZone.setDefault(originalTimeZone); // cleanup
}
}
}
To use it, you need to override the default test suite behavior by adding a method to your TestCase:
public class MyTest extends TestCase {
public static Test suite() {
Test result = new TestSuite(MyTest.class); // default behavior
result = new TimeZoneTestSuite("EST", result); // ensure it runs in EST timezone
return result;
}
TestDecorators are a very powerful feature of JUnit - don't forget about them.