使用组件类进行上下文配置

要使用组件类为测试加载 ApplicationContext(参见 基于 Java 的容器配置),你可以使用 @ContextConfiguration 注解你的测试 类,并使用一个包含对组件类引用的数组来配置 classes 属性。以下示例展示了如何实现:

Java
@ExtendWith(SpringExtension.class)
// ApplicationContext will be loaded from AppConfig and TestConfig
@ContextConfiguration(classes = {AppConfig.class, TestConfig.class}) [id="CO1-1"][id="CO1-1"][id="CO1-1"](1)
class MyTest {
	// class body...
}
<1>  指定组件类。
Kotlin
@ExtendWith(SpringExtension::class)
// ApplicationContext will be loaded from AppConfig and TestConfig
@ContextConfiguration(classes = [AppConfig::class, TestConfig::class]) [id="CO2-1"][id="CO1-2"][id="CO2-1"](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 模式的讨论。

如果你从 @ContextConfiguration 注解中省略 classes 属性,TestContext 框架会尝试检测默认配置类的存在。 具体来说,AnnotationConfigContextLoaderAnnotationConfigWebContextLoader 会检测所有符合配置类实现要求的测试类的 static 嵌套类, 如 @Configuration javadoc 中所述。 请注意,配置类的名称是任意的。此外,如果需要,一个测试类可以包含多个 static 嵌套配置类。 在以下示例中,OrderServiceTest 类声明了一个名为 Configstatic 嵌套配置类,该类会自动用于为测试类加载 ApplicationContext

Java
@SpringJUnitConfig [id="CO3-1"]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` 类加载配置信息。
Kotlin
@SpringJUnitConfig [id="CO4-1"]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` 类加载配置信息。