The unit test keeps giving me =
Wanted but not invoked: However, there were exactly 3 interactions with this mock.
All I am trying to do is, testing the timeout for a method execution - if the method takes more time, then terminate it and publish count(to understand the timed out response rate) as metric.
@Test
public void testTimeoutFunction() throws Exception {
Response response = getResponseForTest();
when(processor
.process(any(Request.class)))
.thenAnswer((Answer<Response>) invocation -> {
Thread.sleep(100);
return response;
});
when(itemRequest.getRequestContext()).thenReturn(itemRequestContext);
testClass = spy(new TestClass(processor, executorService));
List<Item> output = testClass.getItemList(ID, itemRequest);
verify(testClass, times(1)).responseTimedOutCount();
assertTrue(output.isEmpty());
verify(testClass, timeout(EXECUTION_TIMEOUT)).buildResponse(itemRequest);
verify(testClass, times(1)).buildResponse(itemRequest);
}
This is method which I am testing for:
public class TestClass {
@VisibleForTesting
void responseTimedOutCount() {
//log metrics
}
private CompletableFuture<Response> getResponseAsync(final ScheduledExecutorService delayer,
final ItemRequest itemRequest) {
return timeoutWithTimeoutFunction(delayer, EXECUTION_TIMEOUT, TimeUnit.MILLISECONDS,
CompletableFuture.supplyAsync(() -> getResponseWithTimeoutFunction(itemRequest), executorService),
Response.emptyResponse(), () -> responseTimedOutCount());
}
private Response getResponseWithTimeoutFunction(final ItemRequest itemRequest) {
//do something and return response
}
public List<Item> getItemList(final String id, final ItemRequest itemRequest) throws Exception {
final ScheduledExecutorService delayer = Executors.newScheduledThreadPool(1);
Response response;
if(validateItemId(id){
try {
response = getResponseAsync(delayer, itemRequest).get();
} catch (final Throwable t) {
response = Response.emptyResponse();
} finally {
delayer.shutdown();
}
return transform(response, id).getItems();
} else {
return null;
}
}
}
Exception from Junit :
For this assert -
verify(testClass, times(1)).responseTimedOutCount();
Wanted but not invoked:
testClass.responseTimedOutCount();
However, there were exactly 3 interactions with this mock:
testClass.getItemList(ID, itemRequest);
testClass.validateItemId(ID);
testClass.getResponseWithTimeoutFunction(itemRequest);