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. ...
随机推荐
- Postman几种常用方式
Postman几种常用方式 1.get请求直接拼URL形式 对于http接口,有get和post两种请求方式,当接口说明中未明确post中入参必须是json串时,均可用url方式请求 参数既可以写到U ...
- Centos7.2下基于Nginx+Keepalived搭建高可用负载均衡(一.基于Keepalived搭建HA体系)
说明 本文只为方便日后查阅,不对一些概念再做赘述,网上都有很多明确的解释,也请大家先了解相关概念. 两台搭建HA的服务器是华为云上的ECS(不要忘记开通VPC,保证我们的服务器都处在一个内网环境),由 ...
- [转载]在instagram上面如何利用电脑来上传图片
原文地址:在instagram上面如何利用电脑来上传图片作者:小北的梦呓 我们都知道instagram是一个手机版的app,instagram官方不支持通过电脑来上传图片,而利用手机又很麻烦,那么如果 ...
- 201521123107 《Java程序设计》第14周学习总结
第14周-数据库 1.本周学习总结 2.书面作业 1. MySQL数据库基本操作 建立数据库,将自己的姓名.学号作为一条记录插入.(截图,需出现自己的学号.姓名) 在自己建立的数据库上执行常见SQL语 ...
- 201521123109《java程序设计》第八周学习总结
1. 本周学习总结 1.1 以你喜欢的方式(思维导图或其他)归纳总结集合与泛型相关内容. 1.2 选做:收集你认为有用的代码片段 2. 书面作业 本次作业题集集合 List中指定元素的删除(题目4-1 ...
- 201521123013 《Java程序设计》第5周学习总结
1. 本章学习总结 1.1 尝试使用思维导图总结有关多态和接口的知识点. 1.2可选 使用常规方法总结其他上课内容. 接口:不是类,不能使用new实例化,可用instanceof判断是否实现某接口.接 ...
- [转载]sqlserver、Mysql、Oracle三种数据库的优缺点总结
一.sqlserver优点:易用性.适合分布式组织的可伸缩性.用于决策支持的数据仓库功能.与许多其他服务器软件紧密关联的集成性.良好的性价比等:为数据管理与分析带来了灵活性,允许单位在快速变化的环境中 ...
- java课程设计——猜数游戏
1.团队课程设计博客链接 http://www.cnblogs.com/springbreezemiles/p/7064135.html 2.个人负责模块或任务说明 本人任务: 编写主界面以及排行榜代 ...
- 2017年9月19日 JavaScript语法操作
关于JavaScript个人还是觉得比较有意思的 {在</html>后面写或者在</body>前面写(必须紧贴</body>)} <script> va ...
- Tiled Editor 图块的两种导入方式
一.图块集图块的导入. 打开或者创建地图后,新建 新图块. 弹出新图块面板 图块类型选择 "基于图块集图块",一定要选择"嵌入地图",否则需要另存为其他类型的文 ...