Unit testing time-bound code
- by maasg
I'm currently working on an application that does a lot of time-bound operations. That is, based on long now = System.currentTimeMillis();, and combined with an scheduler, it will calculate periods of time that parametrize the execution of some operations. e.g.:
public void execute(...) { // executed by an scheduler each x minutes
final int now = (int) TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis());
final int alignedTime = now - now % getFrequency() ;
final int startTime = alignedTime - 2 * getFrequency();
final int endTimeSecs = alignedTime - getFrequency();
uploadData(target, startTime, endTimeSecs);
}
Most parts of the application are unit-tested independently of time (in this case, uploadData has a natural unit test), but I was wondering about best practices for testing time-bound parts that rely on System.currentTimeMillis() ?