对于最新的稳定版本,请使用 Spring Framework 6.2.0! |
使用组件类的上下文配置
要加载ApplicationContext
对于使用组件类的测试(请参阅基于 Java 的容器配置),您可以对测试
class 替换为@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 | 指定组件类。 |
组件类
术语 “component class” 可以指以下任何内容:
请参阅 javadoc |
如果省略classes
属性@ContextConfiguration
annotation、
TestContext 框架尝试检测是否存在默认配置类。
具体说来AnnotationConfigContextLoader
和AnnotationConfigWebContextLoader
检测全部static
满足
configuration 类实现,如@Configuration
javadoc 的
请注意,配置类的名称是任意的。此外,测试类可以
包含多个static
nested configuration 类。在以下
示例中,OrderServiceTest
class 声明一个static
嵌套配置类
叫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 类。 |