简体   繁体   English

为什么JUnit中的@Rule注释字段必须是公共的?

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

In JUnit test case, a field annotated by @Rule must be public. 在JUnit测试用例中, @Rule注释的@Rule必须是公共的。 It breaks a common Java coding convention (all class member variables should not be public). 它打破了常见的Java编码约定(所有类成员变量都不应该是公共的)。 Why does JUnit require this? 为什么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

The JUnit runner will need to access the field reflectively to run the rule. JUnit运行器需要反射访问该字段以运行规则。 If the field was private the access would throw IllegalAccessException . 如果该字段是私有的,则访问将抛出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返回Rule方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM