本节内容
在之前的教学视频中,很多老师在项目一开始就讲解spring和junit的整合使用,而B站的那位大师到这个阶段才给我们展示了如何在spring项目中使用junit,也算是时机上把握的很好,能够更加让人理解。
不像在视频中教的那样使用很复杂的代码,在本节只用一个简单的例子来说明,主要是给大家介绍在spring项目中写单元测试。
在之前我们是通过编写一个Client.class这样类,在该类中编写main函数来创建ioc 容器,并获取bean对象进行测试,而本节的目的就是编写一个test文件,用来代替main函数。能够更加方便我们进行各种bean 对象的单元测试。
maven配置
为了在spring项目中使用junit,我们需要增加额外的maven 依赖,如下
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
</dependency> 创建测试代码
然后在我们的项目的test目录下面创建测试代码类:
public class AccountServiceTest {
@Test
public void test(){
ApplicationContext ap = new ClassPathXmlApplicationContext("bean.xml");
AccountService ac = ap.getBean("accountService", AccountService.class);
ac.saveAccount();
}
}然后我们执行图中那个绿色的三角,可以看到bean对象中的方法被正确调用了。
存在问题
在上面的实现过程中,如果我们在这个类中要写很多测试方法,那么我们就要不断的复制黏贴ApplicationContext ap = new ClassPathXmlApplicationContext("bean.xml");
AccountService ac = ap.getBean("accountService", AccountService.class);这两句代码,显然这样是不便利的。
解决方案
我们知道junit在执行的时候是有一个main方法的(这样我们在执行的时候才能运行test函数,因为java中main方法是程序运行的入口,在junit的Runner类中),我们要想解决上述问题,除非我们改写junit的main方法,但是显然是不可能的(因为是jar),那如何处理呢?
还好junit给我们提供了重写main方法的的办法,那就是使用@RunWith注解,而spring提供了了一个重写后的class文件(SpringJUnit4ClassRunner.class),这个class是继承了junit中的执行类的。
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>配置上述依赖,因为spring-test需要使用4.12版本以上的junit,所以需要更新一下,然后改写代码如下。
mport com.lujuan.service.impl.AccountService;
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;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:bean.xml")
public class AccountServiceTest {
@Autowired
private AccountService ac;
@Test
public void test(){
ac.saveAccount();
}
}
内容小结
那我们小结一下spring整合junit的步骤:
- 导入maven依赖,junit和spring-test
- 使用junit提供的@Runwith注解,替换原来的main函数
- 告知spring运行器,ioc的创建是基于class还是基于xml配置,并告知配置文件的路径,
@ContextConfiguration(locations = "classpath:bean.xml")和@ContextConfiguration(classes = "config.class") - 然后就可以使用注解方式的依赖注入获取bean对象进行测试了。
不整理不知道,一整理又发现自己已经忘记昨天晚上看的这个知识点了,还是要多总结,多输出。



京公网安备 11010502036488号