繁体   English   中英

Mockito 验证被监视对象方法的返回

[英]Mockito verify the return of a spied object method

我知道你可以验证被监视对象的方法被调用的次数。 你能验证方法调用的结果吗?

像下面这样的?

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

要验证它被调用的次数,请使用verify(spiedObject, times(x)).doSomething()

您不应该验证从间谍对象返回的值。 它不是被测试的对象,所以为什么要验证它返回的内容。 而是验证被测对象的行为以响应从间谍返回的值。

此外,如果您不知道间谍对象将返回什么值,那么最好使用模拟而不是间谍。

TL; 博士
我提供了一个测试模板,您可以在其中验证SpyBean方法返回的内容。 该模板使用 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());
    }
}

既然这样,那就不碍事了 在某些情况下,您需要验证您的 SpyBean 是否正在返回结果值。 例如,被测方法中有两个内部方法调用会产生相同的值。 两者都被调用,但只有其中一个产生想要的结果。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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