我正在尝试编写一个需要使用特定设置的测试类。当只有 1 个设置时,使用 @BeforeEach 很容易:
@BeforeEach public void setup() {
// my setup code
}
@Test public void test1() {
// ...
}
@Test public void test2() {
// ...
}
@Test public void test3() {
// ...
}
但是,当有多种设置可供选择时,我该怎么办?当然,我可以完全忘记 @BeforeEach 并要求同事调用他们想使用的 setup 方法:
@Test public void test1() {
setupA();
// ...
}
@Test public void test2() {
setupB();
// ...
}
@Test public void test3() {
setupB();
// ...
}
但这不再强制使用我的一种设置方法。有没有办法实现“参数化@BeforeEach”?类似于(虚构的语法):
enum SetupType {A, B, C};
@BeforeEach public void setup(SetupType setupType) {
switch (setupType) {
case A:
setupA();
break;
case B:
setupB();
break;
case C:
setupC();
break;
default:
fail("Unrecognized setup.");
}
@Test
@BeforeEachParameter(SetupType.A)
public void test1() {
// ...
}
@Test
@BeforeEachParameter(SetupType.B)
public void test2() {
// ...
}
@Test
@BeforeEachParameter(SetupType.B)
public void test3() {
// ...
}
或者更好的是,将其烘焙到 @Test 注释中?
@TestWithSetupA public void test1() {
// ...
}
@TestWithSetupB public void test2() {
public void test2() {
// ...
}
@TestWithSetupB public void test3() {
public void test3() {
// ...
}