The root of your problem is that the system clock (what gives you the time in a new Date ()
) is not giving you the time you need for your test.
You can avoid this problem by introducing a level of indirection. Instead of having your code directly ask the Java API what the current time is, you have your code ask a Clock
object what the time is. In the real program your Clock
implementation uses the system clock. For your unit tests you use a FakeClock
, which says whatever time you want it to. You tell your code what Clock
to use using dependency injection. You have to write the Clock
interface (or abstract base class) and its concrete implementations yourself.
This approach requires you to alter your existing code, so it is easier to test. Or write it in the first place so it is easier to test. It's one of the tricks of unit testing.
I'm working on some code at the moment that is time sensitive. My clock interface is simply
public interface Clock {
long getCurrentTime ();
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…