Spring整合Junit

续:Spring的新注解
在测试类中,每个测试方法都有以下两行代码:

ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
IAccountService as = ac.getBean("accountService",IAccountService.class);

这两行代码的作用是获取容器,如果不写的话,直接会提示空指针异常。所以又不能轻易删掉。

针对上述问题,我们需要的是程序能自动帮我们创建容器。一旦程序能自动为我们创建 spring 容器,我们就
无须手动创建了,问题也就解决了。

我们都知道junit无法知晓我们是否使用了 spring 框架,更不用说帮我们创建 spring 容器了。不过 junit 提供了一个注解,可以让我们替换掉它的运行器。

Spring提供了一个运行器,可以读取配置文件(或注解)来创建容器。我们只需要告诉它配置文件在哪就行了。这样一来,把 junit的运行器替换为spring的,就可以使程序为我们创建spring容器了——这就是Spring整合Junit。

配置步骤

1、导入spring整合junit的jar包(或maven坐标)

在这里插入图片描述

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>

2、使用@Runwith注解替换原有运行器

使用Junit提供的@Runwith注解,将Junit原有的运行器替换成spring提供的SpringJUnit4ClassRunner。
这个注解的值就是运行器的字节码文件。

@RunWith(SpringJUnit4ClassRunner.class)
public class AccountServiceTest {
	...
}

3、使用@ContextConfiguration 指定 spring 配置文件的位置

@ContextConfiguration注解:

  • locations 属性: 用于指定xml配置文件的位置。如果是类路径下,需要用 classpath:表明。
  • classes 属性: 用于指定注解的类。当不使用 xml 配置时,需要用此属性指定注解类的位置。

两种情况的示例——

  • 使用注解配置:
    在这里插入图片描述
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfiguration.class)
public class AccountServiceTest {
  • 使用xml配置:
    在这里插入图片描述
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations= "classpath:bean.xml")
public class AccountServiceTest {

当我们使用spring 5.x版本的时候,要求junit的jar必须是4.12及以上。

4、使用@Autowired 给测试类中的变量注入数据

在这里插入图片描述

  • 5
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值