加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

spring – @Import vs @ContextConfiguration,用于在单元测试

发布时间:2020-12-15 01:30:08 所属栏目:大数据 来源:网络整理
导读:我能够使用SpringBoot 1.5.3设置并成功运行三种不同的测试配置 方法#1.使用@Import注释导入Bean @RunWith(SpringJUnit4ClassRunner.class)@Import({MyBean.class})public class MyBeanTest() { @Autowired private MyBean myBean;} 方法#2.使用@ContextConfi

我能够使用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
    }

}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读