簡體   English   中英

Mockito doReturn()。when()調用原始方法

[英]Mockito doReturn().when() calls original method

我無法讓Mockito覆蓋正在測試的類中的方法。

@Test
public void test_classToTest() throws Exception {
    DependencyA dependencyA = mock(DependencyA.class);
    DependencyB dependencyB = mock(DependencyB.class);
    DependencyC dependencyC = mock(DependencyC.class);

    ClassToTest classToTest = ClassToTest.builder().dependencyA(dependencyA)
            .dependencyB(dependencyB).dependencyC(dependencyC).build();

    classToTest= Mockito.spy(classToTest);

    Mockito.doReturn("This is not the method you are looking for").when(classToTest).storeContent(null, null, null);

    String result = classToTest.copyContent(someVariable, SOME_CONSTANT);

我試圖覆蓋的方法是classToTest.storeContent(),它是從classToTest.copyContent()內部調用的。 我知道這堂課有點臭,但我無法對其進行重構。 但是,這不是一個非常復雜的設置,我不確定為什么要調用實際的.storeContent()方法。

建議不要使用null參數來設置storeContent方法,而建議使用ArgumentMatchers.any

例如

import static org.mockito.ArgumentMatchers.*;

// ...

Mockito.doReturn("This is not the method you are looking for").when(classToTest).storeContent(any(), any(), any());

Mockito(和其他模擬工具)有一個限制,即不能對final方法進行存根。

也許您的ClassToTest#storeContent標記為final

如果是這種情況,只需刪除final關鍵字,即可啟動存根機制。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM