Spring整合Junit
* 问题:在spring中的junit中无法使用容器的对象
* 分析
1. 程序的运行需要main方法
2. junit的运行可以不需要main方法,只是执行了@Test注解的方法
3. junit不会管我们是否采用spring框架
在执行测试方法时,junit根本不知道我们是不是使用了spring框架
所以也就不会为我们读取配置文件/配置类创建spring核心容器
* 结论:
当测试方法执行时,没有Ioc容器,就算写了Autowired注解,也无法实现注入
* 解决办法:
1. 导入spring整合junit的jar(坐标) spring-test
2. 使用junit提供的一个注解把原有的main方法替换了,替换成spring中提供的
@RunWith:
@RunWith(SpringJUnit4ClassRunner.class)
3. 告知spring的运行器,spring和ioc创建是基于xml还是基于注解的.并且说明位置
@ContextConfiguration
location:指定xml文件的位置,加上classpath关键字,表示在类路径下
@ContextConfiguration(locations = "classpath:ApplicationContext.xml")
classes:指定注解类所在的位置
@ContextConfiguration(classes = SpringConfig.class)
* 当我们使用spring5版本的时候,要求junit的jar包必须是4.1.2以及以上
4. 在使用的时候直接在变量上加@Autowired注解就可以
* 例:
@RunWith(SpringJUnit4ClassRunner.class)
//@ContextConfiguration(locations="classpath:ApplicationContext.xml")//基于xml
@ContextConfiguration(classes = SpringConfig.class)//基于注解
public class SpringJunit {
@Autowired
private IAccountService service;
@Test
public void testFindAll(){
List<Account> all = service.findAll();
for (Account account : all) {
System.out.println(account);
}
}
}