In JUnit test case, a field annotated by @Rule
must be public. It breaks a common Java coding convention (all class member variables should not be public). Why does JUnit require this?
Documentation for @Rule
: https://github.com/junit-team/junit/blob/master/src/main/java/org/junit/Rule.java
To use the JUnit rules, we need to add the @Rule annotation in the test. @Rule: It annotates the fields. It refer to the rules or methods that returns a rule. The annotated fields must be public, non-static, and subtypes of the TestRule or MethodRule.
Rules are used to add additional functionality which applies to all tests within a test class, but in a more generic way. For instance, ExternalResource executes code before and after a test method, without having to use @Before and @After .
The JUnit runner will need to access the field reflectively to run the rule. If the field was private the access would throw IllegalAccessException
.
Another option would have been to have the runner modify the access from private to public before running the rule. However that could cause problems in case a security manager is enabled.
If you want to avoid having public fields in your test class you can from JUnit 4.11 annotate methods that return a Rule
with @Rule
or @ClassRule
.
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