使用元件類別進行情境組態

若要使用元件類別 (請參閱基於 Java 的容器組態) 為您的測試載入 ApplicationContext,您可以使用 @ContextConfiguration 註解您的測試類別,並使用包含元件類別參考的陣列來組態 classes 屬性。以下範例展示了如何執行此操作

  • Java

  • Kotlin

@ExtendWith(SpringExtension.class)
// ApplicationContext will be loaded from AppConfig and TestConfig
@ContextConfiguration(classes = {AppConfig.class, TestConfig.class}) (1)
class MyTest {
	// class body...
}
1 指定元件類別。
@ExtendWith(SpringExtension::class)
// ApplicationContext will be loaded from AppConfig and TestConfig
@ContextConfiguration(classes = [AppConfig::class, TestConfig::class]) (1)
class MyTest {
	// class body...
}
1 指定元件類別。
元件類別

術語「元件類別」可以指以下任何一項

  • 使用 @Configuration 註解的類別。

  • 元件(即,使用 @Component@Service@Repository 或其他刻板印象註解註解的類別)。

  • 使用 jakarta.inject 註解註解的符合 JSR-330 標準的類別。

  • 任何包含 @Bean 方法的類別。

  • 任何其他旨在註冊為 Spring 元件(即 ApplicationContext 中的 Spring bean)的類別,可能會利用單一建構子的自動裝配,而無需使用 Spring 註解。

請參閱 @Configuration@Bean 的 javadoc,以取得有關元件類別組態和語意的更多資訊,特別注意關於 @Bean Lite 模式的討論。

如果您從 @ContextConfiguration 註解中省略 classes 屬性,TestContext 框架會嘗試偵測預設組態類別的存在。具體來說,AnnotationConfigContextLoaderAnnotationConfigWebContextLoader 會偵測測試類別的所有靜態巢狀類別,這些類別符合 @Configuration javadoc 中指定的組態類別實作要求。請注意,組態類別的名稱是任意的。此外,如果需要,一個測試類別可以包含多個靜態巢狀組態類別。在以下範例中,OrderServiceTest 類別宣告了一個名為 Config 的靜態巢狀組態類別,該類別會自動用於為測試類別載入 ApplicationContext

  • Java

  • Kotlin

@SpringJUnitConfig (1)
// ApplicationContext will be loaded from the static nested Config class
class OrderServiceTest {

	@Configuration
	static class Config {

		// this bean will be injected into the OrderServiceTest class
		@Bean
		OrderService orderService() {
			OrderService orderService = new OrderServiceImpl();
			// set properties, etc.
			return orderService;
		}
	}

	@Autowired
	OrderService orderService;

	@Test
	void testOrderService() {
		// test the orderService
	}

}
1 從巢狀 Config 類別載入組態資訊。
@SpringJUnitConfig (1)
// ApplicationContext will be loaded from the nested Config class
class OrderServiceTest {

	@Autowired
	lateinit var orderService: OrderService

	@Configuration
	class Config {

		// this bean will be injected into the OrderServiceTest class
		@Bean
		fun orderService(): OrderService {
			// set properties, etc.
			return OrderServiceImpl()
		}
	}

	@Test
	fun testOrderService() {
		// test the orderService
	}
}
1 從巢狀 Config 類別載入組態資訊。