0

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

cmodha
  • 105
  • 9
  • Possible duplicates https://stackoverflow.com/questions/24491260/mocking-time-in-java-8s-java-time-api and https://stackoverflow.com/questions/2001671/override-java-system-currenttimemillis-for-testing-time-sensitive-code. [Tutorial](https://www.baeldung.com/java-override-system-time) – y_ug Mar 04 '20 at 12:38
  • I don't feel that it's a duplicate question, as the question is not about how to mock LocalDateTime or clock. The question is about how to measure the number of method invocation for a period of time. – cmodha Mar 04 '20 at 14:29

2 Answers2

1

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.

Pavel Smirnov
  • 4,611
  • 3
  • 18
  • 28
0

You can just let it sleep and then call itself? But then you will hog all the memory. Maybe you can even go so far as to multithread?

Sjardi Djoy Willems
  • 2,453
  • 2
  • 8
  • 9