【发布时间】:2021-08-18 06:30:32
【问题描述】:
在带有 slf4j 和 logback 的 spring-boot 环境中的单元测试中,我想确保 LOGGER.isTraceEnabled() 仅针对特定测试类返回 true。
这样做的原因是,有时我们使用 if (LOGGER.isTraceEnabled()) {...} 保护缓慢且非平凡的代码。在单元测试中,我们希望确保在打开跟踪时它不会破坏应用程序。
被测代码:
public class ClassUnderTest{
private static final Logger LOGGER = LoggerFactory.getLogger(ClassUnderTest.class);
public void doSomething(Calendar gegenwart) {
if (LOGGER.isTraceEnabled()) {
// non trivial code
}
}
}
测试代码:
public class ClassUnderTestUnitTest{
@Test
public void findeSnapshotMitLueke() {
ClassUnderTest toTestInstance = new ClassUnderTest ();
// I want to make sure trace logging is enabled, when
// this method is executed.
// Trace logging should not be enabled outside this
// test class.
toTestInstance.doSomething(Calendar.getInstance());
}
}
【问题讨论】:
-
您到底想测试什么?当启用跟踪或仅针对此特定类启用跟踪时,非平凡代码是否有效?
-
非平凡的代码有效。
标签: java spring-boot junit logback slf4j