JUnit 5中的@TestInstance注释有什么用? [英] What use is @TestInstance annotation in JUnit 5?
问题描述
您能否简单解释一下@TestInstance
注释以及它在JUnit 5中如何有用?
Can you give a simple explanation of @TestInstance
annotation and how it can be useful in JUnit 5?
我认为我们可以通过使字段为静态 来实现相同的效果.
I think we can achieve the same effect probably by making our fields static.
推荐答案
I think the docs provide a useful summary:
如果您希望JUnit Jupiter在同一个测试实例上执行所有测试方法,只需使用@TestInstance(Lifecycle.PER_CLASS)注释您的测试类.使用此模式时,每个测试类将创建一个新的测试实例.因此,如果您的测试方法依赖于实例变量中存储的状态,则可能需要在@BeforeEach或@AfterEach方法中重置该状态.
If you would prefer that JUnit Jupiter execute all test methods on the same test instance, simply annotate your test class with @TestInstance(Lifecycle.PER_CLASS). When using this mode, a new test instance will be created once per test class. Thus, if your test methods rely on state stored in instance variables, you may need to reset that state in @BeforeEach or @AfterEach methods.
与默认的按方法"模式相比,按类"模式具有一些其他优点.特别是,通过按类"模式,可以在非静态方法以及接口默认方法上声明@BeforeAll和@AfterAll.因此,每类"模式还可以在@Nested测试类中使用@BeforeAll和@AfterAll方法.
The "per-class" mode has some additional benefits over the default "per-method" mode. Specifically, with the "per-class" mode it becomes possible to declare @BeforeAll and @AfterAll on non-static methods as well as on interface default methods. The "per-class" mode therefore also makes it possible to use @BeforeAll and @AfterAll methods in @Nested test classes.
但是您可能已经读过了,并且认为将字段设为静态与将字段声明为实例变量并使用@TestInstance(Lifecycle.PER_CLASS)
具有相同的效果.
But you've probably read that already and you are correct in thinking that making a field static will have the same effect as declaring the field as an instance variable and using @TestInstance(Lifecycle.PER_CLASS)
.
因此,也许在JUnit 5中如何有用"这个问题的答案是使用@TestInstance
...
So, perhaps the answer to the question "how it could be useful in JUnit 5" is that using a @TestInstance
...
- 明确表示您的意图.可以假定使用static关键字是偶然的,而
@TestInstance
的使用不太可能是偶然的,或者是尽管复制-n-paste较少的结果. - 委托管理范围和生命周期并清理框架的责任,而不必记住自己进行管理.
- Is explicit about your intentions. It could be assumed that use of the static keyword was accidental whereas use of
@TestInstance
is less likely to be accidental or a result of thoughless copy-n-paste. - Delegates the responsibility for managing scope and lifecycle and clean up to the framework rather than having to remember to manage that yourself.
这篇关于JUnit 5中的@TestInstance注释有什么用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!