如何验证单元测试是否记录了错误

时间:2015-10-10 03:20:12

标签: java unit-testing logging junit mockito

假设我有以下类:

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的单元测试看起来像这样:

@Test
public void testTerribleCase() throws ModuleException {
  myMethod("terrible"); 
  //Log should contain "This is terrible!" or assert that error was logged
}

有没有办法确定日志中包含特定的字符串“这太糟糕了”?或者更好的是,有没有办法确定它是否记录了一个错误而没有查找特定的字符串值?

1 个答案:

答案 0 :(得分:2)

创建自定义过滤器以查找消息并记录是否曾见过。

docker@default:~$ docker run -it ubuntu bash
root@2dd12b770666:/# man ls
bash: man: command not found
root@2dd12b770666:/# whereis man
man: /usr/local/man /usr/share/man
root@2dd12b770666:/# export PATH=/usr/local/man:/usr/share/man:$PATH
root@2dd12b770666:/# echo $PATH
/usr/local/man:/usr/share/man:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
root@2dd12b770666:/# man
bash: man: command not found
root@2dd12b770666:/#