一.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集成JUnit单元测试框架的更多相关文章

  1. Spring 集成Junit单元测试

    1.在pom增加junit和spring-test <dependency> <groupId>junit</groupId> <artifactId> ...

  2. Spring完全基于Java配置和集成Junit单元测试

    要点: 配置继承WebApplicationInitializer的类作为启动类,相当于配置web.xml文件 使用@Configuration注解一个类,在类中的方式使用@Bean注解,则表名该方法 ...

  3. Spring系列之新注解配置+Spring集成junit+注解注入

    Spring系列之注解配置 Spring是轻代码而重配置的框架,配置比较繁重,影响开发效率,所以注解开发是一种趋势,注解代替xml配置文件可以简化配置,提高开发效率 你本来要写一段很长的代码来构造一个 ...

  4. JUnit单元测试框架的使用

    http://blog.csdn.net/mao520741111/article/details/51462215 原文地址 http://www.open-open.com/lib/view/op ...

  5. Spring的AOP开发入门,Spring整合Junit单元测试(基于ASpectJ的XML方式)

    参考自 https://www.cnblogs.com/ltfxy/p/9882430.html 创建web项目,引入jar包 除了基本的6个Spring开发的jar包外,还要引入aop开发相关的四个 ...

  6. 学习 Spring Boot:(二十九)Spring Boot Junit 单元测试

    前言 JUnit 是一个回归测试框架,被开发者用于实施对应用程序的单元测试,加快程序编制速度,同时提高编码的质量. JUnit 测试框架具有以下重要特性: 测试工具 测试套件 测试运行器 测试分类 了 ...

  7. Java - Junit单元测试框架

    简介 Junit : http://junit.org/ JUnit是一个开放源代码的Java语言单元测试框架,用于编写和运行可重复的测试. 多数Java的开发环境都已经集成了JUnit作为单元测试的 ...

  8. 原创:Spring整合junit测试框架(简易教程 基于myeclipse,不需要麻烦的导包)

    我用的是myeclipse 10,之前一直想要用junit来测试含有spring注解或动态注入的类方法,可是由于在网上找的相关的jar文件进行测试,老是报这样那样的错误,今天无意中发现myeclips ...

  9. Java反射学习总结终(使用反射和注解模拟JUnit单元测试框架)

    转载请注明本文出自大苞米的博客(http://blog.csdn.net/a396901990),谢谢支持! 本文是Java反射学习总结系列的最后一篇了,这里贴出之前文章的链接,有兴趣的可以打开看看. ...

随机推荐

  1. netty源码解解析(4.0)-10 ChannelPipleline的默认实现--事件传递及处理

    事件触发.传递.处理是DefaultChannelPipleline实现的另一个核心能力.在前面在章节中粗略地讲过了事件的处理流程,本章将会详细地分析其中的所有关键细节.这些关键点包括: 事件触发接口 ...

  2. netty源码解解析(4.0)-9 ChannelPipleline的默认实现-链表管理

    io.netty.channel.DefaultChannelPipeline implements ChannelPipleline   DefaultChannelPiple给出了ChannelP ...

  3. 共享内存 - shmget填坑记

    1. 问题引出 最近有个项目,需要两个进程之间传递大量的数据,因此考虑采用了共享 内存机制+信号同步,两个进程,笔者和另外一程序员开发,协议都定好了,开发很顺利. 等到我们联合调试的时候,问题出现了, ...

  4. 5步搭建GO环境

    Easy Go Programming Setup for Windows Dec 23, 2014 I’ve had to do this more than once recently, so I ...

  5. WebForm 小项目【人员管理系统】分析

    简单的人员管理系统 展示页面 添加人员 --判断添加人员的各种条件限制 -- 各种提示 修改人员信息 -- 人员原来信息绑定 --密码不显示,密码不改时用原来密码 人员删除 using System; ...

  6. 如何对付运行时可能为 null 的 Record Type

    在 F# 中,Record Type 是无法表达 null 语义的,例如,一个 Record 变量不能够使用 null 字面量赋值,接收 nullable(这里并不是指 BCL 中的 Nullable ...

  7. session持久化到sqlserver

    每次想使用都会忘记单词,所幸记录下来.简单步骤记录. 第一步:找到cmd目录 输入:cd C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727 进入该目录. 第二 ...

  8. java反射与动态代理的理解

    一.什么是反射机制? 反射的官方定义是这样的:在运行状态中,对于任意的一个类,都能够知道这个类的所有属性和方法,对任意一个对象都能够通过反射机制调用一个类的任意方法,这种动态获取类信息及动态调用类对象 ...

  9. SVN多分支开发模式V1.0.1

    1目的 规范开发模式过程,指导项目研发.质控测试.DevOps的相关活动. 2适用范围 本规范的作用范围是为互联网软件产品相关项目开发模式的管理过程. (1)   对项目团队中研发人员在开发模式过程中 ...

  10. HTML中令人惊喜的全局属性

    1.accesskey 属性 : 规定激活元素的快捷键. 浏览器支持:几乎所有浏览器均 accesskey 属性,除了 Opera. 定义和用法 accesskey 属性规定激活(使元素获得焦点)元素 ...