Noah Martin
Noah Martin

Reputation: 1809

How to use passed parameter in other method calls?

I have read that I can use the Answer object for this but in my case there is a problem. The situation is like this:

SecondObject secondObject = firstObject.getByType(String type);

then

List list = secondObject.getSomeOtherValues();

Practically I want to use the argument type when mocking the call for the secondObject. Is this possible?

Upvotes: 0

Views: 46

Answers (1)

ahll
ahll

Reputation: 2417

Do something like:

when(firstObject.getByType(anyString())).thenAnswer(
     new Answer() {
         public Object answer(InvocationOnMock invocation) {
             String type= invocation.getArguments()[0];
             SecondObject  second = Mockito.mock(SecondObject  );

             //do something
            if(type== ....){
                when(second.getSomeOtherValues() ).thenReturn(....)
            } else{
                .....................................
            }


             return second ;
         }
 });

SecondObject secondObject = firstObject.getByType(String type);

I have not tested it, but the key is

 if(type== ....){
        when(second.getSomeOtherValues() ).thenReturn(....)
    } else{
        .....................................
    }

And the home page of mockito answer http://static.javadoc.io/org.mockito/mockito-core/2.8.9/org/mockito/stubbing/Answer.html

Upvotes: 1

Related Questions