Junit @Rule and @ClassRule

JavaJunitRule

Java Problem Overview


I am writing JUnit4 test in which I am using TemporaryFolder rule. It seems that it works fine with both @Rule and @ClassRule. What is the difference between Junit @Rule and @ClassRule? Why should I use one and not another?

Java Solutions


Solution 1 - Java

The distinction becomes clear when you have more than one test method in a class.

A @ClassRule has its before() method run before any of the test methods. Then all the test methods are run, and finally the rule's after() method. So if you have five test methods in a class, before() and after() will still only get run once each.

@ClassRule applies to a static method, and so has all the limitations inherent in that.

A @Rule causes tests to be run via the rule's apply() method, which can do things before and after the target method is run. If you have five test methods, the rule's apply() is called five times, as a wrapper around each method.

Use @ClassRule to set up something that can be reused by all the test methods, if you can achieve that in a static method.

Use @Rule to set up something that needs to be created a new, or reset, for each test method.

Solution 2 - Java

@Rule can not be set up to run before an @BeforeClass.

While @ClassRule must be on static method.

Solution 3 - Java

Ref: Annotates static fields that reference rules or methods that return them. A field must be public, static, and a subtype of TestRule. A method must be public static, and return a subtype of TestRule.

The Statement passed to the TestRule will run any BeforeClass methods, then the entire body of the test class (all contained methods, if it is a standard JUnit test class, or all contained classes, if it is a Suite), and finally any AfterClass methods.

https://junit.org/junit4/javadoc/4.12/org/junit/ClassRule.html

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionViktar KavaView Question on Stackoverflow
Solution 1 - JavaslimView Answer on Stackoverflow
Solution 2 - JavaSlavusView Answer on Stackoverflow
Solution 3 - JavaOmprakashView Answer on Stackoverflow