在java中执行测试时打印模式

时间:2016-07-14 05:20:04

标签: java printing junit

目前我们所有的junit测试都遵循约定 -

@Test
public void testXYZ() {
  System.out.println("--------------Testing XYZ-----------");
  // actual test logic goes here
  System.out.println("--------------Successfully tested XYZ-----------");
}

@Test
public void text123() {    
  System.out.println("--------------Testing 123-----------");
  // actual test logic goes here
  System.out.println("--------------Successfully tested 123-----------");
}

如何摆脱这些冗余的打印陈述,但仍然可以展示它们?

1 个答案:

答案 0 :(得分:1)

如果您使用的是较新版本的JUnit,则TestWatcher类可以read the docs

在其页面(未测试)的改编示例下方。

public static class WatchmanTest {
  private static String watchedLog;

  @Rule
  public TestWatcher watchman= new TestWatcher() {
    @Override
    protected void failed(Throwable e, Description description) {
       String methodName = description.getMethodName();
       System.out.println("--------------Failed Test " + methodName + "-----------");   
    }

    @Override
    protected void starting(Description description) {
       String methodName = description.getMethodName();
       System.out.println("--------------Testing " + methodName + "-----------");   
    }

    @Override
    protected void succeeded(Description description) {
       String methodName = description.getMethodName();
       System.out.println("--------------Successfully Tested " + methodName + "-----------");
    }
 };

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

  @Test
  public void TestXYZ() {
      // actual test logic here
      // ...
  }

  @Test
  public void Test123() {
      // actual test logic here
      // ...
  }

}