Spring如何使用junit进行单元测试

这篇文章主要介绍了Spring整合junit单元测试,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧。

目录

    • 整合junit的原因
    • 解决思路分析
    • 配置步骤
      • 1、导入相关依赖
      • 2、编写测试类
    • 总结

整合junit的原因

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

/**
 * @param args
 */
public static void main(String[] args) {
    //1.获取核心容器对象
    ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
    //2.根据id获取Bean对象
    IAccountService as  = (IAccountService)ac.getBean("accountService");
}

解决思路分析

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

我们都知道,junit 单元测试的原理(在 web 阶段课程中讲过),但显然,junit 是无法实现的,因为它自己都无法知晓我们是否使用了 spring 框架,更不用说帮我们创建 spring 容器了。不过好在,junit 给我们暴露了一个注解,可以让我们替换掉它的运行器。

这时,我们需要依靠 spring 框架,因为它提供了一个运行器,可以读取配置文件(或注解)来创建容器。我们只需要告诉它配置文件在哪就行了。

配置步骤

1、导入相关依赖

<dependencies>
     <!-- 提供了springIOC,AOP等 -->
     <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-context</artifactId>
         <version>5.0.2.RELEASE</version>
     </dependency>
	 
	 <!-- junit的Spring测试 -->
     <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-test</artifactId>
         <version>5.0.2.RELEASE</version>
     </dependency>
	 
	 <!-- junit测试 -->
     <dependency>
         <groupId>junit</groupId>
         <artifactId>junit</artifactId>
         <version>4.12</version>
     </dependency>
 </dependencies>

2、编写测试类

@ContextConfiguration 注解:
locations 属性:用于指定配置文件的位置。如果是类路径下,需要用 classpath:表明
classes 属性:用于指定注解的类。当不使用 xml 配置时,需要用此属性指定注解类的位置。
假如配置类为类的形式配置的话就是这样的配置

@ContextConfiguration(classes= SpringConfiguration.class)

下面为xml形式

package com.gzl.test;

import com.gzl.service.IAccountService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

/**
 * 使用Junit单元测试:测试我们的配置
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:bean.xml")
public class AccountServiceTest {

    @Autowired
    private  IAccountService as;

    @Test
    public  void testTransfer(){
        as.transfer("aaa","bbb",100f);

    }

}

也就是他是通过这个注解老告诉junit,我们要整合spring使用,这样我们就可以使用spring的容器及依赖注入了。

@RunWith(SpringJUnit4ClassRunner.class)

总结

感觉小编整理的还可以的,给小编点个赞,哈哈

你可能感兴趣的:(#,Spring,spring)