In JUnit 4.10 and below, it is possible to annotate a rule as both @Rule and @ClassRule. This means the rule gets invoked before before/after the class, and before/after each test. One possible reason for doing so is to set up an expensive external resource (via the @ClassRule calls) and then cheaply reset it (via the @Rule calls).
As of JUnit 4.11, @Rule fields must be non-static and @ClassRule fields must be static, so the above is no longer possible.
There are clearly workarounds (e.g. explicitly separate the @ClassRule and @Rule responsibilities into separate rules), but it seems a shame to have to mandate the use of two rules. I briefly looked at using @Rule and inferring whether or not its the first / last test, but I don't believe that information is available (at least, it's not directly available on Description).
Is there a neat and tidy way of combining the @ClassRule and @Rule functionality in a single rule in JUnit 4.11?
Thanks, Rowan
As of JUnit 4.12 (unreleased at time of writing), it will be possible to annotate a single static rule with both @Rule
and @ClassRule
.
Note that it must be static - a non-static rule annotated with @Rule
and @ClassRule
is still considered invalid (as anything annotated @ClassRule
works at the class level, so only really makes sense as a static member).
See the release notes and my pull request if you're interested in more detail.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With