Reputation: 1329
I'm trying to mock a method when called only from a specific class, as the underlying framework calls my mock method N times.
Is there a way to delineate the invoker of a particular mocked method so I can conditionally return data based on the caller?
I'm using Mockito and the doAnswer API
Upvotes: 1
Views: 246
Reputation: 1198
I think you should be able to return a custom Answer. Using this API you have access to the invocation of the mock. You may be able to use Deadpool's answer and should be able to conditionally return something based on the caller. Help that helps!
Mockito.doAnswer(new Answer<Object>() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
// TODO Auto-generated method stub
// do something with the stack trace
StackTraceElement[] cause = Thread.currentThread().getStackTrace();
return somthing;
}
}).when(service).doSomething();
this question may help: How do I find the caller of a method using stacktrace or reflection?
Upvotes: 1
Reputation: 40078
If you are looking for call hierarchy of method this would be perfect answer
StackTraceElement[] cause = Thread.currentThread().getStackTrace();
From this array you can get all hierarchy class names, so that you check in this array which class called this method
Upvotes: 1