JUnit 4
If you need to stick with JUnit 4, you can use a third-party plugin to provide support. See the junit-hierarchicalcontextrunner provided by bechte
on GitHub.
Add the dependency to your project, and use the HeirachalContextRunner
like so:
@RunWith(HierarchicalContextRunner.class)
public class NestedTest {
@ClassRule
public static final SpringClassRule SPRING_CLASS_RULE = new SpringClassRule();
@Rule
public final SpringMethodRule springMethodRule = new SpringMethodRule();
@Before
public void setup() {
// General test-suite setup
}
public class NestedClass {
@Test
public void testSomething() {
// Test
}
public class AnotherNestedClass {
@Test
public void testSomethingElse() {
// Test
}
}
}
}
Note that we don't need to specify Spring's runner here. Instead, we use the rules to apply the Spring test framework, available as of Spring 4.2
.
JUnit 5
Arguably a more future-proof solution would be to upgrade to JUnit 5
. Then you can construct test cases straight out of the box, with the @Nested
annotation. See below:
@SpringBootTest
@ExtendWith(SpringExtension.class)
class MyNestedTest {
@BeforeAll
void setup() {
// General test-suite setup
}
@Nested
@DisplayName("parentTestSuite")
class NestedClass {
@Test
void testSomething() {
// Test
}
@Nested
@DisplayName("childTestSuite")
class AnotherNestedClass {
@Test
void testSomethingElse() {
// Test
}
}
}
}
Note that @RunWith
has been replaced with @ExtendWith
in JUnit 5
. If you choose to migrate to JUnit 5, you may find it useful to read Baeldung's guide on JUnit 5 migration.