如何使Mockito参数匹配方法签名

时间:2016-09-20 21:42:07

标签: java unit-testing mocking mockito

我试图验证我的代码是否在错误情况下记录了正确的消息,因此我嘲笑了org.apache.commons.logging.Log并且我试图验证它是否被调用正确。

我想要验证的方法的签名是:error(Object, Throwable)我希望传入的字符串包含其他各种内容,但包含文字&#34 ;消息对于队列而言太大了#34;。在这种情况下,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.matches()替换为Mockito.any()则会传递。

1 个答案:

答案 0 :(得分: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));
    }
}