34

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

1 Answer 1

34

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.

Sign up to request clarification or add additional context in comments.

5 Comments

+1 You can also annotate a method with @Rule, so this would avoid the problem. You should add this to your answer.
Thanks Matthew, I did not know that. Apparently new functionality in 4.11.
@KErlandsson - are You completely sure about that? This is what the JUnit API documentation states: "A field must be public, not static, and a subtype of TestRule (preferred) or MethodRule"
@dziki What do you refer to? Am I sure about what exactly?
But if it uses reflexion, it should be able to work with private fields. Not sure why it does not.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.