How to make the arguments of the Mockito method match the signature of the method

I am trying to verify that the correct message is being logged by my code in an error state, so I made fun of it org.apache.commons.logging.Log, and I am trying to verify that it is being called correctly.

The signature of the method I want to test is: error(Object, Throwable)I expect the passed string to have many other things, but includes the text "Message is too large for the queue." In this case, the abandoned will be empty.

Here is my code confirming this:

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

When this is done, I get an error message:

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
);

It seems that the problem is that it Mockito.matches()forces us to look for a method with a signature (String, Throwable) when the actual signature (Object, Throwable).

? , String , Mockito.matches() Mockito.any(), .

+4
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));
    }
}
+1

Source: https://habr.com/ru/post/1655253/


All Articles