运行单元测试时,我想在记录ERROR级别消息的任何测试中失败。使用SLF4J / Logback实现此目的的最简单方法是什么?我想避免编写自己的ILoggerFactory实现。
我尝试编写自定义Appender,但我无法通过调用Appender的代码传播异常,Appender的所有异常都会被捕获。
答案 0 :(得分:5)
关键是编写自定义appender。你不会说你使用哪个单元测试框架,但是对于JUnit我需要做类似的事情(它比所有错误稍微复杂一点,但基本上是相同的概念),并创建了一个添加的JUnit @Rule我的appender,并且appender根据需要未通过测试。
我将此代码的代码放在公共领域:
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.AppenderBase;
import org.junit.rules.ExternalResource;
import org.slf4j.LoggerFactory;
import static org.junit.Assert.fail;
/**
* A JUnit {@link org.junit.Rule} which attaches itself to Logback, and fails the test if an error is logged.
* Designed for use in some tests, as if the system would log an error, that indicates that something
* went wrong, even though the error was correctly caught and logged.
*/
public class FailOnErrorLogged extends ExternalResource {
private FailOnErrorAppender appender;
@Override
protected void before() throws Throwable {
super.before();
final LoggerContext loggerContext = (LoggerContext)(LoggerFactory.getILoggerFactory());
final Logger rootLogger = (Logger)(LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME));
appender = new FailOnErrorAppender();
appender.setContext(loggerContext);
appender.start();
rootLogger.addAppender(appender);
}
@Override
protected void after() {
appender.stop();
final Logger rootLogger = (Logger)(LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME));
rootLogger.detachAppender(appender);
super.after();
}
private static class FailOnErrorAppender extends AppenderBase<ILoggingEvent> {
@Override
protected void append(final ILoggingEvent eventObject) {
if (eventObject.getLevel().isGreaterOrEqual(Level.ERROR)) {
fail("Error logged: " + eventObject.getFormattedMessage());
}
}
}
}
使用示例:
import org.junit.Rule;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ExampleTest {
private static final Logger log = LoggerFactory.getLogger(ExampleTest.class);
@Rule
public FailOnErrorLogged failOnErrorLogged = new FailOnErrorLogged();
@Test
public void testError() {
log.error("Test Error");
}
@Test
public void testInfo() {
log.info("Test Info");
}
}
testError方法失败,testInfo方法通过。如果测试调用了记录错误的真正的测试类,它的工作方式也是一样的。
答案 1 :(得分:0)
因此,如果调用记录器的任何错误报告消息,您希望测试用例失败。
答案 2 :(得分:0)
日志框架通常设计为不向用户抛出任何异常。另一个选项(除了Raedwald的回答)将创建一个自定义appender,在记录ERROR消息时将静态布尔标志设置为true,在setup方法中重置此标志并在拆解方法中检查它(或者创建一个JUnit规则来重置/检查标志。)