使用组件类进行上下文配置
要通过使用组件类(参见基于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 | 指定组件类。 |
|
组件类
“组件类”一词可以指以下任何一种:
有关组件类的配置和语义的更多信息,请参阅 |
如果你省略@ContextConfiguration注解中的classes属性,TestContext框架会尝试检测默认配置类的存在。具体来说,AnnotationConfigContextLoader和AnnotationConfigWebContextLoader会检测测试类的所有static嵌套类,这些类满足@Configuration javadoc中指定的配置类实现要求。请注意,配置类的名称是任意的。此外,如果需要,一个测试类可以包含多个static嵌套配置类。在下面的示例中,OrderServiceTest类声明了一个名为Config的static嵌套配置类,该类会自动用于为测试类加载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类加载配置信息。 |