小伙伴们,你们好,我是老寇
问题描述:无法注入bean
问题分析:
1.查看@SpringBootTest源码
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@BootstrapWith(SpringBootTestContextBootstrapper.class)
public @interface SpringBootTest {
/**
* explicit classes are defined the test will look for nested
* 这句话的意思是 如果没有指定class的情况下,会去该测试类所在的包及子包下面搜索启动类,如果没有则注入为空,
* 如果指定class,则会将扫描到的类组件加载到测试环境
*/
Class<?>[] classes() default {};
}
2.增加@RunWith注解
RunWith就是一个运行器
@RunWith(SpringJUnit4ClassRunner.class) 运行spring测试环境
这里,我们使用@RunWith(SpringRunner.class)
补:小伙伴可能会问了,这里不是应该使用SpringJUnit4ClassRunner?为什么使用SpringRunner?
//这里使用SpringRunner没毛病
public final class SpringRunner extends SpringJUnit4ClassRunner {
public SpringRunner(Class<?> clazz) throws InitializationError {
super(clazz);
}
}
正确写法
@SpringBootTest(classes = {QueryApplication.class})
@RunWith(SpringRunner.class)
@Slf4j
public class QueryApplicationTest {
@Autowired
private DataSource dataSource;
@Test
public void test() {
log.info(dataSource.toString());
}
}
注:如果与启动类是同一个包及子包,就没有必要指定@SpringBootTest的classes