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.


Implementing TestRule

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

public class PerformanceLogger implements TestRule {

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

Using our TestRule

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

  public void testMethod1() throws InterruptedException {
      System.out.println("running testMethod1()");

  public void testMethod2() throws InterruptedException {
      System.out.println("running testMethod2()");

  public void testMethod3() throws InterruptedException {
      System.out.println("running testMethod3()");
mvn -q test -Dtest=MyTestClass


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


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

    See Also