如何解决具有昂贵设置的 Junit ParameterizedTest
我正在寻找一种通过昂贵的设置来优化运行多个参数化测试的方法
我当前的代码是这样的
@ParameterizedTest
@MethodSource("test1CasesProvider")
void test1(String param) {
// expensive setup code 1
// execution & assertions
}
@ParameterizedTest
@MethodSource("test2CasesProvider")
void test2(String param) {
// expensive setup code 2
// execution & assertions
}
但是在这种情况下,每个测试用例都运行昂贵的设置,这不是很好
我可以将此测试拆分为两个单独的测试并使用 @BeforeAll
,然后设置每个测试只运行一次,但我正在寻找一种方法将两种情况都保留在一个测试中
解决方法
在这种情况下,您可以使用 @Nested
测试,如下所示:
public class MyTests {
@Nested
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class Test1Cases {
@BeforeAll
void setUpForTest1() {
System.out.println("Test1Cases: setting up things!");
}
@AfterAll
void tearDownForTest1() {
System.out.println("Test1Cases: tear down things!");
}
@ParameterizedTest
@MethodSource("source")
void shouldDoSomeTests(String testCase) {
System.out.println("Test1Cases: Doing parametrized tests: " + testCase);
}
Stream<Arguments> source() {
return Stream.of(
Arguments.of("first source param!"),Arguments.of("second source param!"),Arguments.of("third source param!")
);
}
}
@Nested
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class Test2Cases {
@BeforeAll
void setUpForTest2() {
System.out.println("Test2Cases: setting up things!");
}
@AfterAll
void tearDownForTest2() {
System.out.println("Test2Cases: tear down things!");
}
@ParameterizedTest
@MethodSource("source")
void shouldDoSomeTests(String testCase) {
System.out.println("Test2Cases: Doing parametrized tests: " + testCase);
}
Stream<Arguments> source() {
return Stream.of(
Arguments.of("first source param!"),Arguments.of("third source param!")
);
}
}
}
这种情况下的输出是:
Test2Cases: setting up things!
Test2Cases: Doing parametrized tests: first source param!
Test2Cases: Doing parametrized tests: second source param!
Test2Cases: Doing parametrized tests: third source param!
Test2Cases: tear down things!
Test1Cases: setting up things!
Test1Cases: Doing parametrized tests: first source param!
Test1Cases: Doing parametrized tests: second source param!
Test1Cases: Doing parametrized tests: third source param!
Test1Cases: tear down things!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。