如何验证单元测试是否记录了错误 [英] How to verify that error was logged with unit tests
本文介绍了如何验证单元测试是否记录了错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有以下这样的类:
Let's say I have the following class like this:
public class MyClass {
public static final Logger LOG = Logger.getLogger(MyClass.class);
public void myMethod(String condition) {
if (condition.equals("terrible")) {
LOG.error("This is terrible!");
return;
}
//rest of logic in method
}
}
我的单元测试 MyClass
看起来像这样:
My unit test for MyClass
looks something like this:
@Test
public void testTerribleCase() throws ModuleException {
myMethod("terrible");
//Log should contain "This is terrible!" or assert that error was logged
}
是否有某种方法可以确定日志包含特定的字符串这很可怕?或者更好的是,有没有办法确定它是否记录了一个错误而没有查找特定的字符串值?
Is there some way to determine that the log contains the specific String "This is terrible"? Or even better, is there a way to determine if it logged an error at all without looking for a specific String value?
推荐答案
创建自定义过滤器以查找消息并记录是否曾见过。
Create a custom filter to look for the message and record if it was ever seen.
@Test
public void testTerribleCase() throws ModuleException {
class TerribleFilter implements Filter {
boolean seen;
@Override
public boolean isLoggable(LogRecord record) {
if ("This is terrible!".equals(record.getMessage())) {
seen = true;
}
return true;
}
}
Logger log = Logger.getLogger(MyClass.class.getName());
TerribleFilter tf = new TerribleFilter();
log.setFilter(tf);
try {
myMethod("terrible");
assertTrue(tf.seen);
} finally {
log.setFilter(null);
}
}
这篇关于如何验证单元测试是否记录了错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文