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

要通过使用组件类(参见基于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.