简体   繁体   中英

Mockito verify the return of a spied object method

I know you can verify the times a spied object's method was called. Can you verify the result of the method call?

Something like the following?

verify(spiedObject, didReturn(true)).doSomething();

To verify the number of times it was invoked, use verify(spiedObject, times(x)).doSomething() .

You should NOT be verifying the value returned from the spied object. It is not the object under test so why verify what it returns. Instead verify the behavior of the object under test in response to the value returned from the spy.

Also, if you don't KNOW what value will be returned by the spied object it would be better to use a mock instead of a spy.

TL;DR
I am providing a template for tests where you want to verify what SpyBean method is returning. The template is using Spring Boot.

@SpringJUnitConfig(Application.class)
public class Test extends SpringBaseTest
{
    @SpyBean
    <replace_ClassToSpyOn> <replace_classToSpyOn>;

    @InjectMocks
    <replace_ClassUnderTest> <replace_classUnderTest>;

    // You might be explicit when instantiating your class under test.
    // @Before
    // public void setUp()
    // {
    //   <replace_classUnderTest> = new <replace_ClassUnderTest>(param_1, param_2, param_3);
    // }

    public static class ResultCaptor<T> implements Answer
    {
        private T result = null;
        public T getResult() {
            return result;
        }

        @Override
        public T answer(InvocationOnMock invocationOnMock) throws Throwable {
            result = (T) invocationOnMock.callRealMethod();
            return result;
        }
    }

    @org.junit.Test
    public void test_name()
    {
        // Given
        String expString = "String that the SpyBean should return.";
        // Replace the type in the ResultCaptor bellow from String to whatever your method returns.
        final Test.ResultCaptor<String> resultCaptor = new Test.ResultCaptor<>();
        doAnswer(resultCaptor).when(<replace_classToSpyOn>).<replace_methodOnSpyBean>(param_1, param_2);

        // When
        <replace_classUnderTest>.<replace_methodUnderTest>(param_1, param_2);

        // Then
        Assert.assertEquals("Error message when values don't match.", expString, resultCaptor.getResult());
    }
}

Now that this is out of the way . There are situations where you would want to verify that your SpyBean is returning the result value. For example, there are two internal method invocations in your method under test that would produce the same value. Both get invoked but only one of them produces the wanted result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM