Java:在JUnit中使用记录器断言*

shr*_*000 5 java logging junit assert

我想要做的是像JUnit中的以下内容:

assertTrue(logger.error("the condition is not true"), <a boolean condition>);
Run Code Online (Sandbox Code Playgroud)

所以记录器记录错误消息,记录器可以是例如commons或log4j.

但Junit断言不接受记录器参数,所以有没有办法实现这一点,或者我是否需要尝试捕获断言并在catch块中记录错误消息?

Mat*_*ell 20

您可以使用JUnit TestRule TestWatcher.A TestRule在测试方法之前和之后执行代码(类似于@Before@After),但您可以访问更多信息,更重要的是,可以访问测试结果.一个TestWatcher定义了类似的方法succeeded(),failed(),starting()并且finished(),它可以实现得到通知的事件.

以下示例仅使用失败的断言打印出失败的测试.

public class TestWatcherTest {
  @Rule
  public TestWatcher testWatcher = new TestWatcher() {
    protected void failed(Throwable e, Description description) {
      System.out.println("" + description.getDisplayName() + " failed " + e.getMessage());
      super.failed(e, description);
    }

  };

  @Test
  public void test1() {
    Assert.assertEquals("hello world", 3, 4);
  }
}
Run Code Online (Sandbox Code Playgroud)

你可以显然做你喜欢的而不是System.out.println().这产生了输出:

test1(uk.co.farwell.junit.TestWatcherTest) failed hello world expected:<3> but was:<4>
Run Code Online (Sandbox Code Playgroud)

请注意,失败的断言是一个例外,因此您可以访问堆栈跟踪等.

  • @duffymo TestWatcher于4.9中引入,它是作为TestWatchman的替代品而引入的,它本身是在4.7中引入的.TestWatchman略有不同,它使用的是MethodRule,现已弃用. (2认同)