Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why @Rule annotated fields in JUnit has to be public?

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

like image 1000
Shuhai Shen Avatar asked Jan 15 '13 10:01

Shuhai Shen


People also ask

What is @rule annotation in JUnit?

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.

What does @rule do Java?

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 .


1 Answers

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.

like image 93
K Erlandsson Avatar answered Sep 17 '22 14:09

K Erlandsson