问题描述
您能否简单解释一下@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:
与默认的按方法"模式相比,按类"模式具有一些其他优点.特别是,通过按类"模式,可以在非静态方法以及接口默认方法上声明@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注释有什么用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!