Created
June 3, 2011 07:09
JUnit Rule for Testing Logging with Logback
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.List; | |
import java.util.Vector; | |
import org.junit.rules.TestWatchman; | |
import org.junit.runners.model.FrameworkMethod; | |
import org.slf4j.LoggerFactory; | |
import ch.qos.logback.classic.Level; | |
import ch.qos.logback.classic.Logger; | |
import ch.qos.logback.classic.LoggerContext; | |
import ch.qos.logback.classic.spi.ILoggingEvent; | |
import ch.qos.logback.core.read.ListAppender; | |
public class LogStub extends TestWatchman { | |
public enum LogLevel { | |
TRACE(Level.TRACE), | |
DEBUG(Level.DEBUG), | |
INFO(Level.INFO), | |
WARN(Level.WARN), | |
ERROR(Level.ERROR); | |
Level internalLevel; | |
private LogLevel(Level level) { | |
this.internalLevel = level; | |
} | |
} | |
private final ListAppender<ILoggingEvent> listAppender = new ListAppender<ILoggingEvent>(); | |
private final LoggerContext lc = (LoggerContext) LoggerFactory | |
.getILoggerFactory(); | |
private final Vector<Class> loggingSources = new Vector<Class>(); | |
private LogLevel level = LogLevel.TRACE; | |
@Override | |
public void starting(FrameworkMethod method) { | |
before(); | |
} | |
@Override | |
public void finished(FrameworkMethod method) { | |
after(); | |
} | |
public void before() { | |
resetLoggingContext(); | |
for (Class logSource : loggingSources) { | |
addAppenderToType(logSource); | |
} | |
listAppender.start(); | |
} | |
public void after() { | |
listAppender.stop(); | |
resetLoggingContext(); | |
} | |
public void record(LogLevel level) { | |
this.level = level; | |
} | |
public void recordLoggingForObject(Object sut) { | |
Class type = sut.getClass(); | |
recordLoggingForType(type); | |
} | |
public <T> void recordLoggingForType(Class<T> type) { | |
loggingSources.add(type); | |
addAppenderToType(type); | |
} | |
public boolean containes(String loggingStatement) { | |
List<ILoggingEvent> list = listAppender.list; | |
for (ILoggingEvent event : list) { | |
if (event.getFormattedMessage().contains(loggingStatement)) { | |
return true; | |
} | |
} | |
return false; | |
} | |
public int size() { | |
return listAppender.list.size(); | |
} | |
private <T> void addAppenderToType(Class<T> type) { | |
Logger logger = (Logger) LoggerFactory.getLogger(type); | |
logger.addAppender(listAppender); | |
logger.setLevel(level.internalLevel); | |
} | |
private void resetLoggingContext() { | |
lc.reset(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment