簡體   English   中英

嘲笑時無效的匹配器

[英]invalid matchers when mocking

我想測試這種方法:

public void some_method(SomeFactory someFactory) {
        A a = someFactory.populateWithParameter(parameter1, parameter2, parameter3, parameter4); 
        a.method_call();
        ....   
    }

工廠就是這樣

public class SomeFactory(){

 // some constructor
public A populateWithParameter(SomeClass1 someClass1, SomeClass2 someClass2, String string, int parameter){
 return new A(someClass1, someClass2, string, parameter)
} 
}

測試是

public void testSomeMethod() throws Exception {
        SomeFactory someFactory = mock(SomeFactory.class);
        when(someFactory.populateWithParameter(
                any(SomeClass1.class), any(SomeClass2.class),
             anyString(), anyInt())).thenReturn(notNull());

        mainActivity.some_method(someFactory);
...
    }

我收到此消息

org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Invalid use of argument matchers!
4 matchers expected, 1 recorded:

不允許使用notNull()作為返回值。 Mockito匹配器僅代表對whenverify調用中的參數,不能用作返回值。 特別是, notNull()實際上會返回null並將“ not null”匹配標記為在隱藏堆棧上的副作用,直到在您與下一個模擬交互之前(當您實際調用some_method ),它都會一直存在。

盡管您沒有列出InvalidUseOfMatchersException堆棧跟蹤,但我敢打賭,該錯誤實際上是在您通過some_method 調用 populateWithParameter時發生的,而不是在對populateWithParameter進行存根處理時發生populateWithParameter “記錄的1個”匹配器不是notNull() ,其中“預期的4個匹配器”是指方法調用中的參數數量。 錯誤消息的確是針對以下情況量身定制的:您忘記為某些參數使用匹配器,例如populateWithParameter(any(), any(), anyString(), 42) ,這是一個非常常見的錯誤。

盡管我在評論中看到“它不起作用!” 當您嘗試返回實例時,我可以保證絕對返回notNull()會引起問題,而返回實例可能只是揭示了一個不同的問題。 切換到返回實例后,您可能想用完整的堆棧跟蹤更新問題,或者提出新問題。

有關幕后Mockito匹配器的更多信息,請在此處查看我的問題/答案

暫無
暫無

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

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