Pages

Friday, December 14, 2018

How to intercept logging in JUnit?

How to intercept logging in JUnit?

I was working on a task to improve the code coverage of a package. It was dealing with logs.
Basically requirement was to intercept the logs, meaning when that method is invoked, some logs need to be generated; which is required to be verified programmatically.The reference URL mentioned here was helpful to accomplish the same.

CODE:

// Required Classes
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.read.ListAppender;
import ch.qos.logback.classic.Logger;


ILoggingEvent event = null;
ListAppender<ILoggingEvent> listAppender = new ListAppender<>();
listAppender.start();



//localLogger reference to the logger object, that the method uses to log the data.

Logger localLogger = (ch.qos.logback.classic.Logger) objectVar;
localLogger.addAppender(listAppender);
methodInvoked();



//Ensure the some logs  are written and able to intercept the same. If logs are generated, they //would be added in the listAppender.list

assertThat(listAppender.list.size() > 0).isTrue();

//Parse / read a log message being intercepted

event = listAppender.list.get(0);
 

//Ensure some log is intercepted
assertThat(event).isNotNull();
 

//Ensure some required pattern appear in the log messages
assertThat(event.getFormattedMessage().contains("Service") && event.getFormattedMessage().contains("Started"))
                        .isTrue();

//stop and detach the listAppender
listAppender.stop();
localLogger.detachAndStopAllAppenders();


Reference:

https://stackoverflow.com/questions/29076981/how-to-intercept-slf4j-logging-via-a-junit-test

No comments:

Post a Comment