简体   繁体   中英

Print a pattern while executing test in java

Currently all our junit tests are following a convention using -

@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-----------");
}

How can I get rid of these redundant print statements but still have them on display?

If you are using a newer version of JUnit, you can read the docs for the TestWatcher class.

Below an adapted example from their page ( not tested ).

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
      // ...
  }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM