Issue
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?
Solution
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.
Answered By - slim
Answer Checked By - Gilberto Lyons (JavaFixing Admin)