Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
286 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...