gpt4 book ai didi

spring - 用于在单元测试中导入 bean 的 @Import 与 @ContextConfiguration

转载 作者:行者123 更新时间:2023-12-03 14:39:29 32 4
gpt4 key购买 nike

我能够使用 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
除了文档中的示例之外,您还可以覆盖 env。与 @TestPropertySource如果您需要在不使用真实属性的情况下在环境中注入(inject)属性。

@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
}

}

关于spring - 用于在单元测试中导入 bean 的 @Import 与 @ContextConfiguration,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44364115/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com