微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

spring – @Import vs @ContextConfiguration,用于在单元测试中导入bean

我能够使用SpringBoot 1.5.3设置并成功运行三种不同的测试配置

方法#1.使用@Import注释导入Bean

@RunWith(SpringJUnit4ClassRunner.class)
@Import({MyBean.class})
public class MyBeantest() {
    @Autowired
    private MyBean myBean;
}

方法#2.使用@ContextConfiguration批注导入Bean

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {MyBean.class})
public class MyBeantest() {
    @Autowired
    private MyBean myBean;
}

方法#3(内部类配置;基于the official blog post)

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader=AnnotationConfigContextLoader.class)
public class MyBeantest() {

    @Configuration
    static class ContextConfiguration {
        @Bean
        public MyBean myBean() {
            return new MyBean();
        }
    }

    @Autowired
    private MyBean myBean;

}

考虑@Import注释文档

Indicates one or more {@link Configuration @Configuration} classes to
import.

并且事实上MyBean不是一个配置类,而是一个用@Component注释注释的bean类,它看起来像方法#1是不正确的.

来自@ContextConfiguration文档

{@code @ContextConfiguration} defines class-level Metadata that is
used to determine how to load and configure an {@link
org.springframework.context.ApplicationContext ApplicationContext}
for integration tests.

听起来它更适用于单元测试,但仍然应该加载一种配置.

方法#1和#2更短更简单.
方法#3看起来是正确的方法.

我对吗?是否还有其他标准为什么我应该使用方法#3,如性能还是别的什么?

最佳答案
如果选择#3选项,实际上不需要指定加载器. From the doc
除了doc中的示例,您还可以覆盖env.如果您需要在环境中注入属性而不使用真实属性,则使用@TestPropertySource.

@RunWith(springrunner.class)
// ApplicationContext will be loaded from the
// static nested Config class
@ContextConfiguration
@TestPropertySource(properties = { "timezone = GMT","port: 4242" })
public class OrderServiceTest {

    @Configuration
    static class Config {

        // this bean will be injected into the OrderServiceTest class
        @Bean
        public OrderService orderService() {
            OrderService orderService = new OrderServiceImpl();
            // set properties,etc.
            return orderService;
        }
    }

    @Autowired
    private OrderService orderService;

    @Test
    public void testOrderService() {
        // test the orderService
    }

}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐