2016-09-20 37 views
4

我試圖驗證在錯誤情況下我的代碼記錄了正確的消息,所以我嘲笑了org.apache.commons.logging.Log,並試圖驗證它是否正確調用。如何使Mockito參數匹配方法簽名

我期待驗證的方法的簽名是:error(Object, Throwable)我期望有一個傳入的字符串,其中包含文本「消息對於隊列太大」。在這種情況下,throwable將爲null。

這裏是我的代碼來驗證這一點:

Mockito.verify(errorLog, Mockito.atLeastOnce()).error(
    Mockito.matches("*Message is too big for queue*"), 
    Mockito.isNull(Throwable.class)); 

在運行此,我雖然得到一個錯誤:

Argument(s) are different! Wanted: 
log.error(
    matches("*Message is too big for queue*"), 
    isNull() 
); 
-> at com.company.TestClass.testMessageTooBig(TestClass.java:178) 
Actual invocation has different arguments: 
log.error(
    |ClassUnderTest|Message is too big for queue (size=41). It will never fit, so discarding., 
    null 
); 

看來,這裏的問題是,這Mockito.matches()使得它看起來對當實際簽名是(Object,Throwable)時帶有簽名(String,Throwable)的方法。

如何讓這些匹配?我知道字符串是問題,因爲如果我用Mockito.any()替換Mockito.matches()它會通過。

+0

如果您刪除,會發生什麼的開頭和結尾從你的論點到Mockito.matches的星號?我在想這可能會使正則表達式匹配。 – unigeek

+1

[ArgumentCaptor](http://site.mockito.org/mockito/docs/current/org/mockito/ArgumentCaptor.html)可能是您的案例中的一個選項 – Mindaugas

+0

我嘗試了ArgumentCaptor並且沒有幫助: 'Argument (s)是不同的!求購: log.error( [email protected], 空 );' – Steve

回答

1

也許一個例子會在這裏有所幫助。看看你能否理解這一點。這可能是有點做作,但它應該讓你有點接近反正..

Main.java

package com.company; 

import org.apache.commons.logging.Log; 
import org.apache.commons.logging.LogFactory; 

public class Main { 
    private static Log log = LogFactory.getLog(Main.class); 

    public Main(Log l) { 
     this.log = l; 
    } 

    public static void main(String[] args) { 
     Main m = new Main(log); 
     m.go(); 
    } 

    public void go() { 
     log.info("this is a test of the emergency broadcasting system.", null); 
    } 
} 

MainTest.java

package com.company; 

import org.apache.commons.logging.Log; 
import org.junit.Test; 
import org.mockito.Mockito; 

import static org.mockito.Matchers.*; 

public class MainTest { 
    Log mockLogger = (Log) Mockito.mock(Log.class); 

    private Main testSubject = new Main(mockLogger); 

    @Test 
    public void should_use_logger() { 
     //Mockito.doNothing().when(mockLogger).info(anyString(), any()); 
     testSubject.go(); 
     Mockito.verify(mockLogger, Mockito.times(1)).info(contains("emergency broadcasting"), isNull(Throwable.class)); 
    } 
}