Search code examples
javajunit

How to unit test a time related method?


Suppose we have this interface:

interface CallChecker {
    boolean canCall(String ipAddress, Object method);
}

And we limit 10 calls per second from one IP for each method, i.e. if a method is called more than 10 times in one second, CallChecker::canCall(ip, method) should return false.

How do we unit test this function?

Side question: is there a better way to define method instead of Object type?


Solution

  • At some point you have to register the timestamp of individual requests to see of they are > 1 and spans for less than 1 second.

    In runtime, you will use eg system clock, Instant.now() or whatever. In unit tests, you will set those timestamps manually. Something like (conceptual only):

    t0=Instant.now();
    for(int i=1;i++;i<=10){
      yourService.handleRequest(request,t0.plusMilis(i*10));
      assertThat(yourSrvice.canMakeRequest).isTrue();
    }
      yourService.handleRequest(request,t0.plusMilis(300));
      assertThat(yourSrvice.canMakeRequest).isFalse();
    

    Now you are free to simulate timelapse by setting request timestamps at will. That is just one of possibilities.