JUnit - Understanding @ClassRule

[Last Updated: Jul 26, 2017]

The annotation @ClassRule can be used as an alternative to @Rule annotation.

It must be used on a static TestRule fields/methods.

The life cycle of such rule execution is on class level rather than on instance level, which is similar to the static methods annotated with @BeforeClass.

Let's understand how it works.


In this example, we are going to reuse our PerformanceLogger from the last example.

public class MyTestClass {
  public static 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-class-rule>mvn -q test -Dtest=MyTestClass
running testMethod1()
running testMethod2()
running testMethod3()
Time taken for com.logicbig.example.MyTestClass: 454 milli sec

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 @ClassRule Example Select All Download
  • junit-class-rule
    • src
      • test
        • java
          • com
            • logicbig
              • example

    See Also