Alex Rivera | Logout

Handling unit tests with a condition on the current time

Asked 2010-08-11T14:05:24.550
16

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.

  1. Should I not bother to test 'isValid', and just test 'isLicenseStringValid()' and the 'getExpiryDate()' function separately?
  2. Do I just use a license key in the test with a crazy long expiry such that I'll have switched jobs by the time it expires?
  3. Do I try to mock out 'new Date()' to some 'getCurrentTime()' method such that I can fake what time it is now?

What do others normally do with tests that are time-conditional?

Edit
Report

1 Answer

2

If you feel the TimeProvider/Clock abstraction is too overboard perfectionist (which may very well be the case), consider this instead

Make getCurrentType protected virtual, then create a TestingProductionType decendant of the ProductionType that contains the code you posted. In that type, override the getCurrentType() method to return some deterministic result. In your unit test, create an instance of this TestingProductionType instead.

Viola, the dependency of current time is now removed from your unit tests. The only production code that is now not unit tested is a method with a single line returning new Date(). I could live with that.

answered 2010-08-11T14:30:15.210

Your Answer