JUnit @Before 与 @Rule

JUnit @Before vs @Rule

我明白了,

假设我需要在每个测试方法之前初始化一些数据,

我如何决定使用 @Before 还是 @Rule?在什么条件下一个人比​​另一个人更受欢迎?同样的问题也适用于@BeforeClass vs.@ClassRule

为了使用 @Rule,您需要一个实现 TestRule(首选)或 MethodRule 的 class,如 here 所示。 @Before@After 需要在每个测试用例中编写一个新方法,而 @Rule 不需要,因为它只是现有代码的实例化。

因此,如果您将在许多测试用例中使用 @Before@After 作为 setUp()tearDown(),这实际上是一个更好的选择使用 @Rule 的想法是因为 code reuse。如果您有一个测试用例需要唯一的 @Before and/or @After,那么这些注释是更可取的。

要通过几个示例获得更详尽的答案,请查看 here。 Ajit 解释得很好。

的确,正如@Quwin 所建议的那样,根据 JUnit 4.12 API doc

TestRule can do everything that could be done previously with methods annotated with @Before, @After, @BeforeClass, or @AfterClass, but TestRules are (1) more powerful, and (2) more easily shared between projects and classes.


TestRule更强大的方式

TestRule 的 类 是已知的实现,它们是您可以开箱即用的一些有用规则,

For examples of how this can be useful, see these provided TestRules, or write your own:

  • ErrorCollector: collect multiple errors in one test method
  • ExpectedException: make flexible assertions about thrown exceptions
  • ExternalResource: start and stop a server, for example
  • TemporaryFolder: create fresh files, and delete after test
  • TestName: remember the test name for use during the method
  • TestWatcher: add logic at events during method execution
  • Timeout: cause test to fail after a set time
  • Verifier: fail test if object state ends up incorrect

规则的另一个好处是可以在单个测试用例中使用多个规则。您可能希望使用 RuleChain 来指定规则的顺序 运行.