Spring+JUnit4单元测试入门
一.JUnit介绍
JUnit是Java中最有名的单元测试框架,用于编写和运行可重复的测试,多数Java的开发环境都已经集成了JUnit作为单元测试的工具。好的单元测试能极大的提高开发效率和代码质量。
测试类命名规则:被测试类+Test,如UserServiceTest
测试用例命名规则:test+用例方法,如testGet
Maven导入junit、sprint-test 、json-path相关测试包,并配置maven-suerfire-plugin插件,编辑pom.xml
<dependencies>
<!-- Test Unit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.3.10.RELEASE</version>
<scope>test</scope>
</dependency>
<!-- Json断言测试 -->
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>2.4.0</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<!-- 单元测试插件 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.20</version>
<dependencies>
<dependency>
<groupId>org.apache.maven.surefire</groupId>
<artifactId>surefire-junit4</artifactId>
<version>2.20</version>
</dependency>
</dependencies>
<configuration>
<!-- 是否跳过测试 -->
<skipTests>false</skipTests>
<!-- 排除测试类 -->
<excludes>
<exclude>**/Base*</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
二.Service层测试示例
创建Service层测试基类,新建BaseServiceTest.java
// 配置Spring中的测试环境
@RunWith(SpringJUnit4ClassRunner.class)
// 指定Spring的配置文件路径
@ContextConfiguration(locations = {"classpath*:/spring/applicationContext.xml"})
// 测试类开启事务,需要指定事务管理器,默认测试完成后,数据库操作自动回滚
@Transactional(transactionManager = "transactionManager")
// 指定数据库操作不回滚,可选
@Rollback(value = false)
public class BaseServiceTest {
}
测试UserService类,新建测试类UserServiceTest.java
public class UserServiceTest extends BaseServiceTest { private static final Logger LOGGER = LoggerFactory.getLogger(UserServiceTest.class); @Resource
private UserService userService; @Test
public void testGet() {
UserDO userDO = userService.get(1); Assert.assertNotNull(userDO);
LOGGER.info(userDO.getUsername()); // 增加验证断言
Assert.assertEquals("testGet faield", "Google", userDO.getUsername());
}
}
三.Controller层测试示示例
创建Controller层测试基类,新建BaseControllerTest.java
// 配置Spring中的测试环境
@RunWith(SpringJUnit4ClassRunner.class)
// 指定测试环境使用的ApplicationContext是WebApplicationContext类型的
// value指定web应用的根
@WebAppConfiguration(value = "src/main/webapp")
// 指定Spring容器层次和配置文件路径
@ContextHierarchy({
@ContextConfiguration(name = "parent", locations = {"classpath*:/spring/applicationContext.xml"}),
@ContextConfiguration(name = "child", locations = {"classpath*:/spring/applicationContext_mvc.xml"})
})
// 测试类开启事务,需要指定事务管理器,默认测试完成后,数据库操作自动回滚
@Transactional(transactionManager = "transactionManager")
// 指定数据库操作不回滚,可选
@Rollback(value = false)
public class BaseControllerTest {
}
测试IndexController类,新建测试类IndexControllerTest.java
public class IndexControllerTest extends BaseControllerTest { private static final Logger LOGGER = LoggerFactory.getLogger(UserServiceTest.class); // 注入webApplicationContext
@Resource
private WebApplicationContext webApplicationContext; private MockMvc mockMvc; // 初始化mockMvc,在每个测试方法前执行
@Before
public void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.webApplicationContext).build();
} @Test
public void testIndex() throws Exception {
/**
* mockMvc.perform()执行一个请求
* get("/server/get")构造一个请求
* andExpect()添加验证规则
* andDo()添加一个结果处理器
* andReturn()执行完成后返回结果
*/
MvcResult result = mockMvc.perform(get("/server/get")
.param("id", "1"))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.username").value("Google"))
.andDo(print())
.andReturn(); LOGGER.info(result.getResponse().getContentAsString()); // 增加验证断言
Assert.assertNotNull(result.getResponse().getContentAsString());
}
}
四.执行单元测试
工程测试目录结构如下,运行mvn test命令,自动执行maven-suerfire-plugin插件
执行结果
五.异常情况
执行测试用例时可能抛BeanCreationNotAllowedException异常
[11 20:47:18,133 WARN ] [Thread-3] (AbstractApplicationContext.java:994) - Exception thrown from ApplicationListener handling ContextClosedEvent
org.springframework.beans.factory.BeanCreationNotAllowedException: Error creating bean with name 'sessionFactory': Singleton bean creation not allowed while singletons of this factory are in destruction (Do not request a bean from a BeanFactory in a destroy method implementation!)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:216)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
at org.springframework.context.event.AbstractApplicationEventMulticaster.retrieveApplicationListeners(AbstractApplicationEventMulticaster.java:235)
at org.springframework.context.event.AbstractApplicationEventMulticaster.getApplicationListeners(AbstractApplicationEventMulticaster.java:192)
at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:128)
通过注入DefaultLifecycleProcessor解决,编辑resources/spring/applicationContext.xml
<bean id="lifecycleProcessor" class="org.springframework.context.support.DefaultLifecycleProcessor">
<property name="timeoutPerShutdownPhase" value="10000"/>
</bean>
Spring+JUnit4单元测试入门的更多相关文章
- JUnit4单元测试入门教程
本文按以下顺序讲解JUnit4的使用 下载jar包 单元测试初体验 自动生成测试类 执行顺序 @Test的属性 下载jar包## 下载地址 在github上,把以下两个jar包都下载下来. 下 ...
- Spring AOP初级——入门及简单应用
在上一篇<关于日志打印的几点建议以及非最佳实践>的末尾提到了日志打印更为高级的一种方式——利用Spring AOP.在打印日志时,通常都会在业务逻辑代码中插入日志打印的语句,这实际上是 ...
- ActiveMQ (三) Spring整合JMS入门
Spring整合JMS入门 前提:安装好了ActiveMQ ActiveMQ安装 Demo结构: 生产者项目springjms_producer: pom.xml <?xml versio ...
- Spring Mvc的入门
SpringMVC也叫Spring Web mvc,属于表现层的框架.Spring MVC是Spring框架的一部分,是在Spring3.0后发布的. Spring Web MVC是什么: Sprin ...
- Spring之单元测试
引言 是否在程序运行时使用单元测试是衡量一个程序员素质的一个重要指标.使用单元测试既可以让我检查程序逻辑的正确性还可以让我们减少程序测试的BUG,便于调试可以提高我们写程序的效率.以前我们做单元测试的 ...
- SpringBoot使用Junit4单元测试
SpringBoot2.0笔记 本篇介绍Springboot单元测试的一些基本操作,有人说一个合格的程序员必须熟练使用单元测试,接下来我们一起在Springboot项目中整合Junit4单元测试. 本 ...
- Spring Cloud 从入门到精通
Spring Cloud 是一套完整的微服务解决方案,基于 Spring Boot 框架,准确的说,它不是一个框架,而是一个大的容器,它将市面上较好的微服务框架集成进来,从而简化了开发者的代码量. 本 ...
- Spring MVC学习总结(1)——Spring MVC单元测试
关于spring MVC单元测试常规的方法则是启动WEB服务器,测试出错 ,停掉WEB 改代码,重启WEB,测试,大量的时间都浪费在WEB服务器的启动上,下面介绍个实用的方法,spring MVC单元 ...
- Spring Junit4 接口测试
Junit实现接口类测试 - dfine.sqa - 博客园http://www.cnblogs.com/Automation_software/archive/2011/01/24/1943054. ...
随机推荐
- 小程序脚本语言WXS详解
WXS脚本语言是 Weixin Script脚本的简称,是JS.JSON.WXML.WXSS之后又一大小程序内部文件类型.截至到目前小程序已经提供了5种文件类型. 解构小程序的几种方式,其中一种方式就 ...
- 转:【Java并发编程】之十一:线程间通信中notify通知的遗漏(含代码)
转载请注明出处:http://blog.csdn.net/ns_code/article/details/17228213 notify通知的遗漏很容易理解,即threadA还没开始wait的时候,t ...
- 软件工程——构建之法高分Tips
不想获得高分的学生不是好程序猿,结合助教的经验,要想在这门课程上获得高分先提几个Tips 仔细阅读作业要求,尽可能完成作业的每个点 每次老师作业要求布置的都很详细,想获得高分的同学应该仔细阅读作业要求 ...
- 结对编程1-四则运算GUI实现(58、59)
题目描述 我们在个人作业1中,用各种语言实现了一个命令行的四则运算小程序.进一步,本次要求把这个程序做成GUI(可以是Windows PC 上的,也可以是Mac.Linux,web,手机上的),成为一 ...
- 微信小程序view标签以及display:flex的测试
一:testview.wxml,testview.js自动生成示例代码 //testview.wxml <view class="section"> <view ...
- 团队作业8----第二次项目冲刺(beta阶段)5.24
Day6-05.24 1.每日会议 会议内容: 1.组长林乔桦对昨日的工作进行了总结并且安排今日的任务. 2.阶段进入尾声,大家再一次集中对软件进行了优化讨论. 3.今天主要大家的工作重心放在异常的测 ...
- 团队作业4---第一次项目冲刺(ALpha)版本 第七天
一.Daily Scrum Meeting照片 二.燃尽图 三.项目进展 a.完成所有基础功能 b.正在进行测试调试 四.困难与问题 1.随着测试出现了大大小小的一些BUG,但是由于原来写的时候思维定 ...
- 201521123006 《java程序设计》 第11周学习总结
1. 本周学习总结 1.1 以你喜欢的方式(思维导图或其他)归纳总结多线程相关内容. 2. 书面作业 本次PTA作业题集多线程 1.互斥访问与同步访问 完成题集4-4(互斥访问)与4-5(同步访问) ...
- 工厂模式 and 单例模式
工厂模式:使用工厂类使创建类与使用类分离,从而提高代码的易维护性,可扩展性等 工厂模式分位简单工厂模式和工厂方法模式 使用简单工厂模式的步骤: 1.创建父类及其子类 父类中有[ ...
- PHP面向对象三大特性之一:封装
面向对象的三大特性:封装.继承.多态 1.封装 封装的目的:让类更加安全,做法是不让外界直接访问类的成员 具体做法:1.成员变为私有:访问修饰符(public.private.protected) ...