我的 Spring Boot 应用程序是这样启动的:
new SpringApplicationBuilder()
.sources(ParentCtxConfig.class)
.child(ChildFirstCtxConfig.class)
.sibling(ChildSecondCtxConfig.class)
.run(args);
配置类用@SpringBootApplication
. 结果,我有一个根上下文和两个子 Web 上下文。
我想编写集成测试,我想在那里有相同的上下文层次结构。我至少想ChildFirstCtxConfig.class
用他的父上下文( )测试第一个子上下文(用 配置ParentCtxConfig.class
)。我怎样才能做到这一点?
目前我ApplicationContext
在我的测试中自动接线,所以我可以检查它。我在测试中有这个类注释:
@RunWith(SpringRunner.class)
@SpringBootTest(classes = { ParentCtxConfig.class, ChildFirstCtxConfig.class }, webEnvironment = WebEnvironment.RANDOM_PORT)
但这会产生单一的上下文,我想要父子层次结构。我假设我应该用@ContextHierarchy
注释来注释我的测试。
将我的测试注释更改为此似乎与前面的示例完全相同:
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = { ParentCtxConfig.class, ChildFirstCtxConfig.class })
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
但如果我想介绍@ContextHierarchy
并有这样的东西:
@RunWith(SpringRunner.class)
@ContextHierarchy({
@ContextConfiguration(name = "root", classes = ParentCtxConfig.class),
@ContextConfiguration(name = "child", classes = ChildFirstCtxConfig.class)
})
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
由于在父上下文中定义的 bean 无法在子上下文中找到/自动装配,因此上下文未启动。设置loader = SpringBootContextLoader.class
没有帮助。
示例代码:GitHub