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?
3 Answers
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.
-
Simple, concise to the point –– Different from the official Javadoc. Thanks! Jan 22, 2021 at 23:37
-
Hands down, one of the only few easy explanations that make sense on @ClassRule Feb 21, 2022 at 7:24
-
how about just use annotations BeforeClass and Before? why ClassRule and Rule is needed? May 6, 2022 at 17:08
@Rule can not be set up to run before an @BeforeClass.
While @ClassRule must be on static method.
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