I'm trying to write a test class that requires the use of a certain setup. When there's only 1 setup, this is easy with @BeforeEach:
@BeforeEach public void setup() {
// my setup code
}
@Test public void test1() {
// ...
}
@Test public void test2() {
// ...
}
@Test public void test3() {
// ...
}
But what can I do when there are several setups to choose from? Of course, I could forget the @BeforeEach altogether and ask colleagues to call the setup method they'd like to use:
@Test public void test1() {
setupA();
// ...
}
@Test public void test2() {
setupB();
// ...
}
@Test public void test3() {
setupB();
// ...
}
But this no longer forces the use of one of my setup methods. Is there a way to implement a "parametrized @BeforeEach"? Something like (made-up syntax):
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() {
// ...
}
Or even better, baking it into the @Test annotation?
@TestWithSetupA public void test1() {
// ...
}
@TestWithSetupB public void test2() {
public void test2() {
// ...
}
@TestWithSetupB public void test3() {
public void test3() {
// ...
}