在我的Spring Boot项目中,我有一个被注解为
现在我想编写一个集成测试来启动应用程序的完整上下文。但是,这样做无法正常工作,因为它还会捕获其他单元测试中定义的内部类的Spring上下文。
如何避免这种情况呢?我看到了
更新:
一些代码来更好地说明问题:
我的主类:
@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内部类的beans。我希望避免这种情况。