Below is a method that I am attempting to write Junit test for:
Method I wish to test:
//logger declared outside of method in Class
private static Logger LOGGER = LoggerFactory.getLogger(PersonService.class);
public void showOutputOfIdentifications(int age) {
if(age>25){
LOGGER.info("Over 25");
}else{
LOGGER.info("25 or Under");
}
}
How can I test to verify that the correct Logback
Log statement has been called?
In my tests I have tried to mock the logger
and verify that it was called, however this has not worked?
Current Test Attempt:
@Test
public void testShowOutputOfIdentifications() throws ParseException{
int age = 10;
Logger LOGGER_mock = mock(Logger.class);
//call method under test
showOutputOfIdentifications(age);
verify(LOGGER_mock).info("25 or under");
}
Current failing test output:
Wanted but not invoked:
logger.info(
"25 or under "
);
Actually, there were zero interactions with this mock.
JUnit is a Java unit testing framework that's one of the best test methods for regression testing. An open-source framework, it is used to write and run repeatable automated tests.
You could add your own appender and assert that the log message was written that way, see Programmatically configure LogBack appender.
Something like this:
// create the mock appender
Appender mockedAppender = Mockito.mock(Appender.class);
// inject it
((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME)).addAppender(mockedAppender);
// run your test
LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME).error("Test msg");
// verify using ArgumentCaptor
ArgumentCaptor<Appender> argumentCaptor = ArgumentCaptor.forClass(Appender.class);
Mockito.verify(mockedAppender).doAppend(argumentCaptor.capture());
// assert against argumentCaptor.getAllValues()
Assert.assertEquals(1, argumentCaptor.getAllValues().size());
Assert.assertEquals("Test msg", ((LoggingEvent)argumentCaptor.getAllValues().get(0)).getMessage());
// remove the mock appender from static context
((Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME)).detachAppender(mockedAppender);
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