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
Create some retry delay type that represents the policy for retry delays. Invoke some method on the policy type for the delay. Mock it as you like. No conditional logic, or true
/false
flags. Just inject the type that you want.
In ConnectRetryPolicy.java
public interface ConnectRetryPolicy {
void doRetryDelay();
}
In SleepConnectRetryPolicy.java
public class final SleepConnectRetryPolicy implements ConnectRetryPolicy {
private final int delay;
public SleepConnectRetryPolicy(final int delay) {
this.delay = delay;
}
@Override
public void doRetryDelay() {
try {
Thread.sleep(delay);
} catch (InterruptedException ie) {
log.error("connection delay sleep interrupted", ie);
}
}
}
In MockConnectRetryPolicy.java
public final class MockConnectRetryPolicy implements ConnectRetryPolicy {
@Override
public void doRetryDelay() {
// no delay
}
}