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

前端 未结 1 1892
一生所求
一生所求 2020-12-11 14:28

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

相关标签:
1条回答
  • 2020-12-11 15:18

    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.

    0 讨论(0)
提交回复
热议问题