【发布时间】:2015-12-23 17:04:10
【问题描述】:
在我的 Spring Boot 项目中,我有一个用 @SpringBootConfiguration 注释的主类。我还有一些使用@SpringApplicationConfiguration 的单元测试,它指向一个内部类,该内部类定义了一个Spring 上下文以在我的单元测试中使用(使用一些模拟)。
我现在想编写一个集成测试来启动我的应用程序的完整上下文。但是,这不起作用,因为它还会获取在其他单元测试中定义为内部类的 Spring 上下文。
避免这种情况的最佳方法是什么?我确实在@SpringBootConfiguration 上看到了exclude 和excludeName 属性,但我不确定如何使用它们。
更新:
更多解释问题的代码:
我的主要课程:
package com.company.myapp;
@SpringBootApplication
@EnableJpaRepositories
@EnableTransactionManagement
@EntityScan(basePackageClasses = {MyApplication.class, Jsr310JpaConverters.class})
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
我对 Spring REST Docs 进行了单元测试:
package com.company.myapp.controller
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration
@WebAppConfiguration
public class SomeControllerDocumentation {
@Rule
public final RestDocumentation restDocumentation = new RestDocumentation("target/generated-snippets");
// Some test methods here
// Inner class that defines the context for the unit test
public static class TestConfiguration {
@Bean
public SomeController someController() { return new SomeController(); }
@Bean
public SomeService someService() { return new SomeServiceImpl(); }
@Bean
public SomeRepository someRepository() { return mock(SomeRepository.class);
}
所以单元测试使用内部类中定义的上下文。现在我想要一个不同的测试来测试应用程序的“正常”应用程序上下文是否启动:
package com.company.myapp;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(MyApplication.class)
@WebAppConfiguration
public class MyApplicationTest {
@Autowired
private ApplicationContext applicationContext;
@Test
public void whenApplicationStarts_thenContextIsInitialized() {
assertThat(applicationContext).isNotNull();
}
}
这个测试现在不仅会连接它应该连接的东西,还会连接来自 SomeControllerDocumentation.TestConfiguration 内部类的 bean。这是我想避免的。
【问题讨论】:
标签: java spring unit-testing spring-boot