将JUnit测试列表中的所有错误/失败记录到文本文件中

时间:2013-07-10 20:46:22

标签: java unit-testing junit

我正在编写一个测试工具和一组junit测试来测试各种环境下的各种HTTP方法。目前我已经编写了一堆测试,最终我想要做的是能够将Junit测试中的所有错误/失败输出到文本文件。实现这一目标的最佳方法是什么?

例如,如果测试失败,我想说明junit测试的名称和一些信息(来自Test Harness类,例如响应状态代码和状态代码描述)。

2 个答案:

答案 0 :(得分:1)

尝试使用Apache Log4J

另一种方法是将信息发送到文件。检查this tutorial。当您的测试失败时,您只需append()将信息发送到您的文件。

.append(this.class() + respone.getStatus() + response.getCode());

答案 1 :(得分:0)

您应该使用https://github.com/junit-team/junit/wiki/Rules#testwatchmantestwatcher-rules

上详述的TestWatcher
public class WatchmanTest {
  private static String watchedLog;

  @Rule
  public TestRule watchman = new TestWatcher() {
    @Override
    public Statement apply(Statement base, Description description) {
      return super.apply(base, description);
    }

    @Override
    protected void succeeded(Description description) {
      watchedLog += description.getDisplayName() + " " + "success!\n";
    }

    @Override
    protected void failed(Throwable e, Description description) {
      watchedLog += description.getDisplayName() + " " + e.getClass().getSimpleName() + "\n";
    }

    @Override
    protected void skipped(AssumptionViolatedException e, Description description) {
      watchedLog += description.getDisplayName() + " " + e.getClass().getSimpleName() + "\n";
    }

    @Override
    protected void starting(Description description) {
      super.starting(description);
    }

    @Override
    protected void finished(Description description) {
      super.finished(description);
    }
  };

  @Test
  public void fails() {
    fail();
  }

  @Test
  public void succeeds() {
  }
}

你将实现这些方法,JUnit给你一个fail()方法的回调,导致失败的异常和一个包含更多测试信息的Description对象。 您还应该查看该页面上的ExternalResource类,因为它详细说明了如何可靠地设置和拆除要在TestWatcher中使用的资源,例如您要写入的文件。