在我的代码中,我不想加载 XXApplicationConfig 类中定义的所有 bean。
XXApplicationConfig 是一个带有@Configuration 注释的文件,其中定义了一堆 spring bean。
因此,我想在测试时仅从 XXApplicationConfig 类加载 AppBean,以减少加载测试时间并区分我正在测试的内容。我还想使用 XXApplicationConfig 类加载类,以确保定义的 bean 配置也正确。
这是我测试 AppBean 类的测试类(已修改)。
您能告诉我这是否是正确的方法并建议如何改进吗?目前,这种方法似乎奏效了。但是,不确定这是否是接近它的正确方法。
@ContextConfiguration(loader=AnnotationConfigContextLoader.class)
@RunWith(SpringJUnit4ClassRunner.class)
public class ApplicationTest {
@Configuration
@PropertySources(value = {@PropertySource("classpath:test.properties")})
static class MyTestConfiguration {
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceHolderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
@Bean
public XXApplicationConfig xxAppConfig() {
return new XXApplicationConfig();
}
@Bean
public CustomTestService customTestService() {
return new CustomTestService();
}
@Bean
public AppBean appBean() throws Exception {
return XXApplicationConfig().appBean();
}
}
@Autowired
private AppBean appBean;
@Test
public void testAppBean() {
test appBean.doSomething();
}
}
最佳答案
如果您只想测试一个对象,只需使用该类的构造函数创建该类的一个对象即可。 Spring bean 被设计为 POJO。 Spring 上下文只是一种创建和连接对象的便捷方式。没有什么能阻止您自己创建和连接它们。
关于java - 如何使用现有应用程序的 spring 配置类只测试一个 bean?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25632395/