I'm taking a stab at setting up unit tests for some utility classes in a project I'm working on, and one of the classes (contains licensing info) has a method that does some determination based on the current time.
i.e. the license contains an expiry date, and the license string validates that date, but the actual logic to see if the license is expired is based on the current time.
public boolean isValid()
{
return isLicenseStringValid() && !isExpired();
}
public boolean isExpired()
{
Date expiry = getExpiryDate();
if( expiry == null ) {
return false;
}
Date now = new Date();
return now.after( expiry );
}
So, I'm not sure what to do, since the 'new Date()' thing isn't a static criterion.
What do others normally do with tests that are time-conditional?
Definitely mock out new Date()
.
Create a Clock
interface with a getCurrentTime()
method or something similar. That way you can have a FakeClock
for testing and a SystemClock
which uses System.currentTimeMillis()
or whatever.
I've done this a number of times - it's worked extremely well. It's logical too - effectively you require a "current time service" so that should be injected like any other dependency.
I usually inject a date provider into the tested code. This also helps if you need to switch conventions or otherwise "fix" the time testing code.
Use dependency injection and inject a TimeProvider
that provides a getExpiryDate()
method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With