You can use a for this. Here is the code for the rule:@Rule
import org.joda.time.DateTimeZone;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;
public class UTCRule extends TestWatcher {
private DateTimeZone origDefault = DateTimeZone.getDefault();
@Override
protected void starting( Description description ) {
DateTimeZone.setDefault( DateTimeZone.UTC );
}
@Override
protected void finished( Description description ) {
DateTimeZone.setDefault( origDefault );
}
}
You can use the rule like this:
public class SomeTest {
@Rule
public UTCRule utcRule = new UTCRule();
....
}
This will change the current time zone to UTC before each test in will be executed and it will restore the default time zone after each test.SomeTest
If you want to check several time zones, use a rule like this one:
import org.joda.time.DateTimeZone;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;
public class TZRule extends TestWatcher {
private DateTimeZone origDefault = DateTimeZone.getDefault();
private DateTimeZone tz;
public TZRule( DateTimeZone tz ) {
this.tz = tz;
}
@Override
protected void starting( Description description ) {
DateTimeZone.setDefault( tz );
}
@Override
protected void finished( Description description ) {
DateTimeZone.setDefault( origDefault );
}
}
Put all the affected tests in an abstract base class and extend it:AbstractTZTest
public class UTCTest extends AbstractTZTest {
@Rule public TZRule tzRule = new TZRule( DateTimeZone.UTC );
}
That will execute all tests in with UTC. For each time zone that you want to test, you'll need another class:AbstractTZTest
public class UTCTest extends AbstractTZTest {
@Rule public TZRule tzRule = new TZRule( DateTimeZone.forID( "..." );
}
Since test cases are inherited, that's all - you just need to define the rule.
In a similar way, you can shift the system clock. Use a rule that calls to simulate that the test runs at a certain time and to restore the defaults.DateTimeUtils.setCurrentMillisProvider(...)
DateTimeUtils.setCurrentMillisSystem()
Note: Your provider will need a way to make the clock tick or all new instances will have the same value. I often advance the value by a millisecond each time is called.DateTime
getMillis()
Note 2: That only works with joda-time. It doesn't affect .new java.util.Date()
Note 3: You can't run these tests in parallel anymore. They must run in sequence or one of them will most likely restore the default timezone while another test is running.