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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With