How to override default answers on mockito mock?

I have the following code:

private MyService myService;

@Before
public void setDependencies() {
    myService = Mockito.mock(MyService.class, new StandardServiceAnswer());
    Mockito.when(myService.mobileMethod(Mockito.any(MobileCommand.class), Mockito.any(Context.class)))
            .thenAnswer(new MobileServiceAnswer());
}

My intention is that all appeals to the mocked myServiceshould be answered in a standard way. However, the call mobileMethod(which is publicly available) must answer in a certain way.

What I find is that when I get to the line to add an answer to the calls mobileMethod, instead of attaching MobileServiceAnswer, Java actually calls myService.mobileMethod, which leads to NPE.

Is it possible? It would seem that it should be possible to override the default answer. If possible, what is the right way to do this?

Update

Here are my Answers:

private class StandardServiceAnswer implements Answer<Result> {
    public Result answer(InvocationOnMock invocation) {
        Object[] args = invocation.getArguments();

        Command command = (Command) args[0];
        command.setState(State.TRY);

        Result result = new Result();
        result.setState(State.TRY);
        return result;
    }
}

private class MobileServiceAnswer implements Answer<MobileResult> {
    public MobileResult answer(InvocationOnMock invocation) {
        Object[] args = invocation.getArguments();

        MobileCommand command = (MobileCommand) args[0];
        command.setState(State.TRY);

        MobileResult result = new MobileResult();
        result.setState(State.TRY);
        return result;
    }
}
+4
source share
2

:

Java setState , (null). Java, : Mockito , , , Mockito , mobileMethod when. .

doVerb, doAnswer, doReturn doThrow, Yoda. when(object).method() when(object.method()), Mockito , . :

MyService myService = Mockito.mock(MyService.class, new StandardServiceAnswer());
Mockito.doAnswer(new MobileServiceAnswer())
    .when(myService).mobileMethod(
          Mockito.any(MobileCommand.class), Mockito.any(Context.class));

, - , . "-Verb" , , .thenReturn(...).thenThrow(...). , when(mobileMethod(command, context)) command context , , .

"doVerb-when" "when-thenVerb" , , . : "doVerb" "-Verb", mocks spies. "" - , - , "doVerb" - , .

+15

, , , , :

private Properties props;

@Before 
public void setUp() {
    props = mock(Properties.class, new Answer<String>() {
        @Override
     public String answer(InvocationOnMock invocation) throws Throwable {
         return "foo";
     }
    } );
    when(props.get("override")).thenAnswer(new Answer<String>() {
        @Override
     public String answer(InvocationOnMock invocation) throws Throwable {
         return "bar";
     }
    } );
}

@Test
public void test() {
    assertEquals("foo", props.get("no override"));
    assertEquals("bar", props.get("override"));
}

, , , , .

0

Source: https://habr.com/ru/post/1532862/


All Articles