What are the recommended approaches to using Thread.sleep()
to speed up tests.
I am testing a network library with a retry functionality when connection
I just faced a similar issue and I created a Sleeper
interface to abstract this away:
public interface Sleeper
{
void sleep( long millis ) throws InterruptedException;
}
The default implementation uses Thread.sleep()
:
public class ThreadSleeper implements Sleeper
{
@Override
public void sleep( long millis ) throws InterruptedException
{
Thread.sleep( millis );
}
}
In my unit tests, I inject a FixedDateTimeAdvanceSleeper
:
public class FixedDateTimeAdvanceSleeper implements Sleeper
{
@Override
public void sleep( long millis ) throws InterruptedException
{
DateTimeUtils.setCurrentMillisFixed( DateTime.now().getMillis() + millis );
}
}
This allows me to query the time in a unit test:
assertThat( new DateTime( DateTimeUtils.currentTimeMillis() ) ).isEqualTo( new DateTime( "2014-03-27T00:00:30" ) );
Note that you need to fix the time first using DateTimeUtils.setCurrentMillisFixed( new DateTime( "2014-03-26T09:37:13" ).getMillis() );
at the start of your test and restore the time again after the test using DateTimeUtils.setCurrentMillisSystem();