【问题标题】:How can I test only one bean using existing application's spring configuration class?如何使用现有应用程序的 spring 配置类仅测试一个 bean?
【发布时间】:2014-10-27 06:00:22
【问题描述】:

在我的代码中,我不想加载 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();
    }
}

【问题讨论】:

    标签: java spring spring-4


    【解决方案1】:

    如果您只想测试一个对象,只需使用该类的构造函数创建该类的一个对象。 Spring bean 被设计为 POJO。 Spring 上下文只是一种创建和连接对象的便捷方式。没有什么能阻止您自己创建和连接它们。

    【讨论】:

      【解决方案2】:

      如果您可以实例化您想要测试的类并通过构造函数和/或 setter getter 手动注入它所需的所有依赖项,那么您就不需要在测试中使用 Spring。

      但是,如果你的 bean:

      1. 使用带有@Autowired 或@Value 注释的私有字段,而没有相应的getter/setter。
      2. 取决于许多其他 bean。
      3. 您要测试的行为取决于 Spring AOP/Proxies(例如,您使用 @Transactional 或 @Cacheable)。

      然后你将需要 Spring 来连接 bean。我个人更喜欢为这些情况定义一个最小的@Configuration 类。

      再一次,如果您的 bean 满足列表中的条件,您应该考虑重构 bean 以最小化它的依赖关系并方便测试。

      【讨论】:

        猜你喜欢
        • 2016-04-25
        • 1970-01-01
        • 1970-01-01
        • 2017-07-21
        • 2021-01-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-13
        相关资源
        最近更新 更多