Reputation: 2164
I'm doing the integration test using Mockito, and I'm testing the scenario when a timeout happened do some stuff.
public boolean checkTimeout(){
if (createdAt.isBefore(dateTimeHelper.getNowUtc().minus(PROCESSING_TIMEOUT_MILLIS))) {
return true;
}
return false;
}
In the integration test, the dateTimeHelper.getNowUtc()
method is called 10+ times. And I only want to be mock the time to be current time when checkTimeout()
function is called, and mock the other time to be a stub time, say '2015-11-2 15:20:45'.
Can anyone tell me what's the right way to mock this?
a Brute force way is
doReturn(new DateTime(2015, 11, 2, 15, 30, 45)).doReturn(new DateTime(2015, 11, 2, 15, 30, 45)).......
.doCallRealMethod().when(dateTimeHelperMock).getNowUtc();
Write doReturn()
10+ times, then doCallRealMethod()
which is ugly. And if someone touch the code and add more getNowUtc()
, the test will fail.
I'm new to Mockito, so want to know if there's a way to control the mock when getNowUtc()
is called in checkTimeout()
Upvotes: 1
Views: 303
Reputation: 18764
You Can probably do something like this:
Mockito.when(obj.get()).thenAnswer(new Answer<String>() {
public String answer(InvocationOnMock invocation) throws Throwable
{
StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
for (StackTraceElement element : stackTrace)
{
//logic to iterate over stack trace elemtns and find your method.
}
}
});
Upvotes: 1