Mockito : doAnswer Vs thenReturn

前端 未结 2 1117
礼貌的吻别
礼貌的吻别 2020-12-04 07:38

I am using Mockito for service later unit testing. I am confused when to use doAnswer vs thenReturn.

Can anyone help me in detail? So far,

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-04 07:50

    You should use thenReturn or doReturn when you know the return value at the time you mock a method call. This defined value is returned when you invoke the mocked method.

    thenReturn(T value) Sets a return value to be returned when the method is called.

    @Test
    public void test_return() throws Exception {
        Dummy dummy = mock(Dummy.class);
        int returnValue = 5;
    
        // choose your preferred way
        when(dummy.stringLength("dummy")).thenReturn(returnValue);
        doReturn(returnValue).when(dummy).stringLength("dummy");
    }
    

    Answer is used when you need to do additional actions when a mocked method is invoked, e.g. when you need to compute the return value based on the parameters of this method call.

    Use doAnswer() when you want to stub a void method with generic Answer.

    Answer specifies an action that is executed and a return value that is returned when you interact with the mock.

    @Test
    public void test_answer() throws Exception {
        Dummy dummy = mock(Dummy.class);
        Answer answer = new Answer() {
            public Integer answer(InvocationOnMock invocation) throws Throwable {
                String string = invocation.getArgumentAt(0, String.class);
                return string.length() * 2;
            }
        };
    
        // choose your preferred way
        when(dummy.stringLength("dummy")).thenAnswer(answer);
        doAnswer(answer).when(dummy).stringLength("dummy");
    }
    

提交回复
热议问题