1 回答

TA貢獻1865條經驗 獲得超7個贊
JUnit 4
如果您需要堅持使用 JUnit 4,可以使用第三方插件來提供支持。
將依賴項添加到您的項目中,并HeirachalContextRunner
像這樣使用:
@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
? ? ? ? ? ? }
? ? ? ? }
? ? }
}
請注意,我們不需要在這里指定 Spring 的運行器。相反,我們使用規則來應用 Spring 測試框架,從Spring 4.2.
JUnit 5
可以說,一個更具前瞻性的解決方案是升級到JUnit 5. 然后您可以使用注釋直接構建測試用例@Nested。見下文:
@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
? ? ? ? ? ? }
? ? ? ? }
? ? }
}
請注意,@RunWith
已替換為@ExtendWith
in?JUnit 5
。如果您選擇遷移到 JUnit 5,您可能會發現閱讀Baeldung 的 JUnit 5 遷移指南很有用。
添加回答
舉報