Naman
Naman

Reputation: 32036

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?

Upvotes: 0

Views: 47

Answers (1)

blurfus
blurfus

Reputation: 14031

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

}

Upvotes: 1

Related Questions