John Lippson
John Lippson

Reputation: 1329

doAnswer to check which class called a specific function?

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

Answers (2)

Phil Ninan
Phil Ninan

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();

https://static.javadoc.io/org.mockito/mockito-core/1.10.19/org/mockito/invocation/InvocationOnMock.html

this question may help: How do I find the caller of a method using stacktrace or reflection?

Upvotes: 1

Ryuzaki L
Ryuzaki L

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

Related Questions