使用元件類進行上下文配置

要透過使用元件類(參見基於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或其他原型註解註解的類)。

  • 一個符合JSR-330標準並用jakarta.inject註解的類。

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

  • 任何其他打算註冊為Spring元件(即ApplicationContext中的Spring bean)的類,可能會利用單個建構函式的自動裝配而無需使用Spring註解。

有關元件類的配置和語義的更多資訊,請參閱@Configuration@Bean的javadoc,並特別注意@Bean Lite Mode的討論。

如果你省略@ContextConfiguration註解中的classes屬性,TestContext框架會嘗試檢測預設配置類的存在。具體來說,AnnotationConfigContextLoaderAnnotationConfigWebContextLoader會檢測測試類的所有static巢狀類,這些類滿足@Configuration javadoc中指定的配置類實現要求。請注意,配置類的名稱是任意的。此外,如果需要,一個測試類可以包含多個static巢狀配置類。在下面的示例中,OrderServiceTest類聲明瞭一個名為Configstatic巢狀配置類,該類會自動用於為測試類載入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類載入配置資訊。
© . This site is unofficial and not affiliated with VMware.