簡體   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