小编Ale*_*vic的帖子

基于Spring Boot的测试中的上下文层次结构

我的Spring Boot应用程序启动如下:

new SpringApplicationBuilder()
  .sources(ParentCtxConfig.class)
  .child(ChildFirstCtxConfig.class)
  .sibling(ChildSecondCtxConfig.class)
  .run(args);
Run Code Online (Sandbox Code Playgroud)

配置类使用注释@SpringBootApplication.因此,我有一个根上下文和两个子Web上下文.

我想编写集成测试,我希望在那里有相同的上下文层次结构.我希望至少ChildFirstCtxConfig.class用他的父上下文(ParentCtxConfig.class)测试第一个子上下文(配置).我怎样才能做到这一点?

目前我ApplicationContext在我的测试中自动装配,所以我可以检查它.我在测试中有这个类注释:

@RunWith(SpringRunner.class)    
@SpringBootTest(classes = { ParentCtxConfig.class, ChildFirstCtxConfig.class }, webEnvironment = WebEnvironment.RANDOM_PORT)
Run Code Online (Sandbox Code Playgroud)

但这将产生单个上下文,我想要父子层次结构.我假设我应该用@ContextHierarchy注释来注释我的测试.

将我的测试注释更改为这似乎与前面的示例完全相同:

@RunWith(SpringRunner.class)    
@ContextConfiguration(classes = { ParentCtxConfig.class, ChildFirstCtxConfig.class })
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
Run Code Online (Sandbox Code Playgroud)

但是,如果我想介绍@ContextHierarchy并有这样的事情:

@RunWith(SpringRunner.class)
@ContextHierarchy({
        @ContextConfiguration(name = "root", classes = ParentCtxConfig.class),
        @ContextConfiguration(name = "child", classes = ChildFirstCtxConfig.class)
})
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
Run Code Online (Sandbox Code Playgroud)

由于在父上下文中定义的bean无法在子上下文中找到/自动装配,因此未启动上下文.设置loader = SpringBootContextLoader.class没有帮助.

示例代码:GitHub

java spring spring-test spring-boot spring-boot-test

8
推荐指数
1
解决办法
3445
查看次数