My requirement is to have some initialization done for a set of tests and clear it off once all the tests are complete. These tests spin over a few test classes as they are not closely related, but require a common initialization.
I am using @SelectClasses
to form the suite and trying to make use of @ExtendWith
using a custom extension that should handle the pre and post processing. This does not work and I am unsure if an appropriate solution exists in JUnit. Sharing the sample code of what was already attempted.
Suite:
@SelectClasses({FirstTest.class, SecondTest.class})
@ExtendWith(SuiteExtension.class)
@RunWith(JUnitPlatform.class)
@SuiteDisplayName("test suite")
public class SuiteClass {
}
Extension:
public class SuiteExtension implements BeforeAllCallback, AfterAllCallback {
@Override
public void afterAll(ExtensionContext context) throws Exception {
System.out.println("afterAll");
}
@Override
public void beforeAll(ExtensionContext context) throws Exception {
System.out.println("beforeAll");
}
}
Test Class 1:
public class FirstTest {
@Test
void test1(){
System.out.println("test1");
}
}
Test Class 2:
public class SecondTest {
@Test
void test2(){
System.out.println("test2");
}
}
Output:
test1
test2
Expected Output:
beforeAll
test1
test2
afterAll