javajunitmockingjunit5awaitility

How can I Unit test that a specific method of a class in java was periodically invoked for a given duration


I'm in process of creating an error handler. Which will repeatedly invoke a failed method, with some fixed delays over a given duration.

Example.

I have a service class that interacts with outside world.

class Service {
   void doSomething(); 
}

And I also have an Error handler for that service which will repeatedly invoke service.doSomething() for a duration of 5 min, with some fixed delay for 30 seconds.

class ErrorHandler { 
   private Service service;

   void handle() {
     //repeatedly invoke service.doSomething();
   }
}

How can i write a Unit test for this error handler to test that indeed

service.doSomething()

was repeatedly invoked for the duration of 5 mins. I'm aware that mockito's verificationmode provides different options to verify number of times. But in this case I'm specifically interested to test that a method was repeatedly invoked within a given duration . I've also explored awaitility but not sure if it has any method that can help.

Highly appreciate any suggestions :)

Thanks Chintan


Solution

  • You can do it by mocking doSomething() method and providing your own implementation that records the time the method gets called. Here's an example:

    final List<LocalDateTime> list = new ArrayList<>();
    Service service = Mockito.mock(Service.class);
    Mockito.doAnswer(a -> list.add(LocalDateTime.now())).when(service).doSomething();
    

    In this example each time the method is called, LocalDateTime representing the current timestamp is saved to a list. Finally, all you have to do is to loop through the list, compare neighbouring dates, find the intervals and compare them with the expected value. The interval between the first and the last date will show you the total duration.