1.Junit单元测试中,没有main方法也能执行
Junit集成一个main方法
该方法就会判断当前测试类中那些方法有 @Test注解
Junit就会让Test注解的方法执行
2.Junit不会管我们是否使用spring框架
在执行测试方法时,Junit根本不知道我们是不是使用了spring框架
所以也就不会为我们读取配置文件/配置类创建spring核心容器
3.由以上2点可知
当测试方法执行时,没有IOC容器,就算写了Autowired注解,也无法实现注入
使用Junit单元测试,测试我们的配置
* Spring 整合Junit的配置
* 1.导入spring整合Junit的jar包(坐标)
* 2.使用Junit提供的一个注解吧原有的main方法替换了,替换成spring提供的
* @Runwith
* 3.告知spring的运行器,spring和IOC创建时基于xml还是注解,并说明位置
* @ContextConfiguration
* location :指定xml文件的位置,加上classpath关键字,表示在类路径下
* classes:指定注解类所在的位置
* 当我们使用spring 5.x版本的时候,要求Junit的jar必须是在4.1.2及以上
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=SpringConfiguration.class)
public class AccountServiceTest {
//1.获取容器
//spring自动创建容器得到对象
@Autowired
private AccountService as = null;
@Test
public void testFindAll(){
//3.执行方法
List<Account> accounts = as.findAllAccount();
for (Account account:accounts){
System.out.println(account);
}
}
Junit的问题和整合解释
最新推荐文章于 2021-10-10 14:32:05 发布