Close

JUnit - Implementing JUnit Custom Rule

[Last Updated: Aug 5, 2017]

In this example we will learn how to define our own custom @Rule by implementing TestRule.

Example

Implementing TestRule

This implementation will log the time taken to run each test method.

public class PerformanceLogger implements TestRule {

  @Override
  public Statement apply(Statement base, Description description) {
      return new Statement() {
          @Override
          public void evaluate() throws Throwable {
              long start = System.currentTimeMillis();
              try {
                  base.evaluate();
              } finally {
                  System.out.printf("Time taken for %s: %s milli sec%n",
                          description.getDisplayName(),
                          System.currentTimeMillis() - start);
              }
          }
      };
  }
}

Using our TestRule

public class MyTestClass {
  @Rule
  public PerformanceLogger performanceLogger = new PerformanceLogger();

  @Test
  public void testMethod1() throws InterruptedException {
      System.out.println("running testMethod1()");
      Thread.sleep(200);
  }

  @Test
  public void testMethod2() throws InterruptedException {
      System.out.println("running testMethod2()");
      Thread.sleep(150);
  }

  @Test
  public void testMethod3() throws InterruptedException {
      System.out.println("running testMethod3()");
      Thread.sleep(100);
  }
}
mvn -q test -Dtest=MyTestClass

Output

d:\example-projects\junit\junit-custom-rule>mvn -q test -Dtest=MyTestClass
running testMethod1()
Time taken for testMethod1(com.logicbig.example.MyTestClass): 200 milli sec
running testMethod2()
Time taken for testMethod2(com.logicbig.example.MyTestClass): 150 milli sec
running testMethod3()
Time taken for testMethod3(com.logicbig.example.MyTestClass): 100 milli sec

Note:

If you are interested in implementing a custom rule, it is better to explore existing implementations of TestRule to see what they are doing. Also it might be convenient to extend one of the JUnit base classes like ExternalResource, Verifier or TestWatcher etc to extend the existing functionality.

Example Project

Dependencies and Technologies Used:

  • junit 4.12: JUnit is a unit testing framework for Java, created by Erich Gamma and Kent Beck.
  • JDK 1.8
  • Maven 3.3.9

JUnit Custom TestRule Example Select All Download
  • junit-custom-rule
    • src
      • test
        • java
          • com
            • logicbig
              • example
                • PerformanceLogger.java

    See Also