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.
Example
In this example, we are going to reuse our PerformanceLogger from the last example.
public class MyTestClass {
@ClassRule
public static 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-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.