如何在标记测试后运行清理方法? [英] How can I run cleanup method only after tagged tests?
问题描述
我正在为我的Java项目编写JUnit 5测试。
I'm writing JUnit 5 tests for my Java project.
我有一些测试方法,需要耗费时间进行清理(在每个测试之后)。理想情况下,我想用一些注释标记它们并仅为它们运行清理方法。
I have some test methods that require time consuming clean up (after each of them). Ideally, I would like to mark them with some annotation and run cleanup method only for them.
这是我试过的:
class MyTest {
@AfterEach
@Tag("needs-cleanup")
void cleanup() {
//do some complex stuff
}
@Test
void test1() {
//do test1
}
@Test
@Tag("needs-cleanup")
void test2() {
//do test2
}
}
我希望清理
方法只能在<$ c之后运行$ C> TEST2 。但它实际上在两次测试后运行。
I want cleanup
method to be run only after test2
. But it actually runs after both tests.
是否可以通过JUnit 5注释的某种组合来实现它?我不想将我的测试类分成几个类或直接从测试方法调用 cleanup
。
Is it possible to achieve it via some combination of JUnit 5 annotations? I don't want to split my test class into several classes or call cleanup
from test methods directly.
推荐答案
来自文档:
TestInfo:如果方法参数的类型为TestInfo,则
TestInfoParameterResolver将提供与当前测试对应的TestInfo
实例作为参数的值。然后可以使用
TestInfo来检索有关当前
测试的信息,例如测试的显示名称,测试类,测试方法,
或相关标签。显示名称是技术名称,例如
作为测试类或测试方法的名称,或者是通过@DisplayName配置的自定义名称
。
TestInfo: if a method parameter is of type TestInfo, the TestInfoParameterResolver will supply an instance of TestInfo corresponding to the current test as the value for the parameter. The TestInfo can then be used to retrieve information about the current test such as the test’s display name, the test class, the test method, or associated tags. The display name is either a technical name, such as the name of the test class or test method, or a custom name configured via @DisplayName.
TestInfo从
JUnit 4充当TestName规则的替代品。
TestInfo acts as a drop-in replacement for the TestName rule from JUnit 4.
关于上述说明,你可以使用TestInfo类来提供cleanUp应该运行的类的信息,然后你需要检查条件并通过检查它们的标签来允许你想要的那些:
Regarding above description, you can use TestInfo class which gives you information of the class that cleanUp is supposed to be run for,then you need check the condition and allow those you want by checking their tags:
@AfterEach
void afterEach(TestInfo info) {
if(!info.getTags().contains("cleanItUp")) return; // preconditioning only to needs clean up
//// Clean up logic Here
}
@Test
@Tag("cleanItUp")
void myTest() {
}
这篇关于如何在标记测试后运行清理方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!