我能够使用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.
听起来它更适用于单元测试,但仍然应该加载一种配置.
最佳答案
如果选择#3选项,实际上不需要指定加载器. From the doc
除了doc中的示例,您还可以覆盖env.如果您需要在环境中注入属性而不使用真实属性,则使用@TestPropertySource.
原文链接:https://www.f2er.com/spring/432257.html除了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
}
}