Compare doAnswer and thenReturn methods in Mockito

November 27, 2020 No comments Mockito Java doAnswer thenReturn

1. Introduction

In this article we will answer the question when to use the doAnswer() vs thenReturn() method in Mockito tests.

2. doAnswer() vs thenReturn()

The when(...).thenReturn(...) and doReturn(...).when(...) notations should be used in cases when we know exactly what will be the return value at the time we are mock a method call. This specified value will be returned when we invoke the mocked method.

Let's have a look at the example test:

package com.frontbackend.libraries.mockito;

import static org.mockito.Mockito.doReturn;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;

@RunWith(MockitoJUnitRunner.class)
public class MockitoWhenThenTest {

    interface SomeDummyInterface {
        int getStringLength(String str);
    }

    @Mock
    SomeDummyInterface someDummyInterface;

    @Test
    public void testWhenThenReturn() {
        int returnValue = 5;

        Mockito.when(someDummyInterface.getStringLength("dummy"))
               .thenReturn(returnValue);
        doReturn(returnValue).when(someDummyInterface)
                             .getStringLength("dummy");
    }
}

The Answer is used when we need to do some additional calculations/actions when the mocked method is called. For exapmle, we could compute the return value based on input parameters.

We could also use doAnswer() when we want to stub a void method with a generic Answer.

Let's check the example:

package com.frontbackend.libraries.mockito;

import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.when;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import org.mockito.stubbing.Answer;

@RunWith(MockitoJUnitRunner.class)
public class MockitoWhenThenVsThenAnswerTest {

    interface SomeDummyInterface {
        int getStringLength(String str);
    }

    @Mock
    SomeDummyInterface someDummyInterface;

    @Test
    public void testThenAnswer() {
        Answer<Integer> answer = invocation -> {
            String string = (String) invocation.getArguments()[0];
            return string.length() * 5;
        };

        when(someDummyInterface.getStringLength("dummy")).thenAnswer(answer);
        Mockito.doAnswer(answer)
               .when(someDummyInterface)
               .getStringLength("dummy");
    }
}

In this example, we used an argument that was passed to the mocked method and calculate what result this method should return.

3. Conclusion

In this article, we compare doAnswer() and thenReturn() methods. We showed an example in which cases we should use them.

As usual, the code used in this article is available under our GitHub repository.

{{ message }}

{{ 'Comments are closed.' | trans }}