[英]Junit ParameterizedTest with expensive setup
Im looking for a way of optimize running multiple parameterized tests with expensive setup我正在寻找一种通过昂贵的设置优化运行多个参数化测试的方法
my current code looks like this我当前的代码看起来像这样
@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
}
but in that shape expensive setup runs for every testCase, which is not very good I can split this test into two separate tests and use @BeforeAll
, then setup runs only once per test, but im looking for a way to keep both cases in one test但是在这种情况下,每个测试用例都运行昂贵的设置,这不是很好我可以将此测试分成两个单独的测试并使用@BeforeAll
,然后设置每个测试只运行一次,但我正在寻找一种方法来保持这两种情况在一个测试
You can use @Nested
tests in this case, like this way:在这种情况下,您可以使用@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("second source param!"),
Arguments.of("third source param!")
);
}
}
}
The output in this case was:在这种情况下,output 是:
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!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.