0

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?

Naman
  • 27,789
  • 26
  • 218
  • 353
  • read about aspect oriented programming – Jens Jul 14 '16 at 05:22
  • do you mean besides using `@Before` and `@After` ? – blurfus Jul 14 '16 at 05:23
  • http://stackoverflow.com/questions/473401/get-name-of-currently-executing-test-in-junit-4 – ajb Jul 14 '16 at 05:25
  • @ochi - If they can help, not an issue, but how go i generalise the output – Naman Jul 14 '16 at 05:25
  • 1
    use `@Before` for `System.out.println("--------------Testing -----------");` and `@After` for `System.out.println("--------------Successfully tested -----------");` – pahan Jul 14 '16 at 05:26
  • @ajb - Its not about getting the name of the test, its about optimising the print block code. – Naman Jul 14 '16 at 05:27
  • 1
    @pahan mix that up with test names!!?? – Naman Jul 14 '16 at 05:28
  • Just like @pahan said, create a method for the line printed at the beginning of the test and another method for the line printed at the end. Annotate each accordingly. It should be all you need. If you need to get the name of the test running, combine with @ ajb's proposed answer – blurfus Jul 14 '16 at 05:29

1 Answers1

1

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

}

blurfus
  • 13,485
  • 8
  • 55
  • 61