02.Spring 整合 Junit

问题

  • 在测试类中,每个测试方法都有以下两行代码:
      ApplicationContext ac = new ClassPathXmlApplicationContext(“bean.xml”);
      IAccountService as = ac.getBean(“accountService”,IAccountService.class);
  • 这两行代码的作用是获取容器,如果不写的话,直接会提示空指针异常。所以又不能轻易删掉

解决思路分析

  • 针对上述问题,我们需要的是程序能自动帮我们创建容器。一旦程序能自动为我们创建 spring 容器,我们就 无须手动创建了,问题也就解决了
  • junit 无法知晓我们是否使用了 spring 框架,更不用说帮我们创建 spring 容器了,不过好在,junit 给我们暴露 了一个注解,可以让我们替换掉它的运行器
  • 这时,我们需要依靠 spring 框架,因为它提供了一个运行器,可以读取配置文件(或注解)来创建容器,我们只需要告诉它配置文件在哪就行了

配置步骤

  • 新增依赖坐标
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
  • 使用@RunWith 注解替换原有运行器
@RunWith(SpringJUnit4ClassRunner.class) 
public class AccountServiceTest { 

} 
  • 使用@ContextConfiguration 指定 Spring 配置文件的位置
/**
 * 使用Junit单元测试:测试我们的配置
 * 因为junit不知道我们使用了什么框架,所以不会帮我自动创建bean容器,因此我们要导入spring整合junit的jar包
 * @RunWith 把启动器换成spring整合junit
 * 告知spring的运行器,spring和IOC创建是基于xml还是注解的,并说明配置文件的位置
 * @ContextConfiguration 注解:
 *          属性:
 *              location:指定xml的位置,要加上关键字classpath,指定在类路径下
 *              classes:指定以注解形式配置的配置文件的位置
 */
@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(locations= {"classpath:bean.xml"}) 
public class AccountServiceTest { 

} 
  • 使用@Autowired 给测试类中的变量注入数据
@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(locations= {"classpath:bean.xml"}) 
public class AccountServiceTest { 
	@Autowired 
 	private IAccountService accountService; 
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值