Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to verify arbitrary interaction using Mockito in a compact way?

It is easy to verify that specific interaction (specific method call) occurred on a mock object in Mockito, and there is verifyZeroInteractions() for checking that no interactions occurred at all. Suppose I'm testing an interface such as that of a logger, with methods such as info(), warn(), error() etc. In a specific scenario I know one of these methods should be called, but I don't really care which one. Is there a compact way to check that any interaction with the mock object occurred without the need of specifying which exactly method should be called? Or perhaps such a mechanism is not necessary because "the Mockito way" of testing this would be different from what I imagine?

like image 717
Michał Kosmulski Avatar asked Oct 08 '22 10:10

Michał Kosmulski


1 Answers

With log4j, to test the logger I do the following setup:

@Mock private Appender log4jAppender;
private Logger logger;

@Before
public void setup() {
    MockitoAnnotations.initMocks(this);

    Logger root = Logger.getRootLogger();
    if (!root.getAllAppenders().hasMoreElements()) {
        // No appenders means log4j is not initialized!
        BasicConfigurator.configure();
    }
    logger = Logger.getLogger(MyClassWhichLogs.class);
    logger.addAppender(log4jAppender);
}

and then in my test I do the following:

verifyZeroInteractions(log4jAppender);

or

verify(log4jAppender).doAppend(any(LoggingEvent.class);

If you need to test the values logged, you can provide a captor instead:

ArgumentCaptor<LoggingEvent> logCaptor = ArgumentCaptor.forClass(LoggingEvent.class);
verify(log4jAppender).doAppend(logCaptor.capture());
assertTrue(logCaptor.getValue().contains("my text to match");

While this doesn't necessarily answer the generalized question (I don't think what you're looking for exists), it may solve this specific problem for testing logging.

like image 59
Kevin Welker Avatar answered Oct 11 '22 21:10

Kevin Welker