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?
在JUnit测试用例中,@ Rule注释的字段必须是公共的。它打破了常见的Java编码约定(所有类成员变量都不应该是公共的)。为什么JUnit需要这个?
Documentation for @Rule
: https://github.com/junit-team/junit/blob/master/src/main/java/org/junit/Rule.java
@Rule的文档:https://github.com/junit-team/junit/blob/master/src/main/java/org/junit/Rule.java
1 个解决方案
#1
28
The JUnit runner will need to access the field reflectively to run the rule. If the field was private the access would throw IllegalAccessException
.
JUnit运行器需要反射访问该字段以运行规则。如果该字段是私有的,则访问将抛出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
.
如果要避免在测试类中使用公共字段,可以从JUnit 4.11注释使用@Rule或@ClassRule返回规则的方法。
#1
28
The JUnit runner will need to access the field reflectively to run the rule. If the field was private the access would throw IllegalAccessException
.
JUnit运行器需要反射访问该字段以运行规则。如果该字段是私有的,则访问将抛出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
.
如果要避免在测试类中使用公共字段,可以从JUnit 4.11注释使用@Rule或@ClassRule返回规则的方法。