Spring整合Junit

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);
        }
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值