Spring MVC Controller 单元测试
简介
Controller层的单元测试可以使得应用的可靠性得到提升,虽然这使得开发的时间有所增加,有得必失,这里我认为得到的比失去的多很多。
Sping MVC3.2版本之后的单元测试方法有所变化,随着功能的提升,单元测试更加的简单高效。
这里以4.1版本为例,记录Controller的单元测试流程。非常值得参考的是Spring MVC Showcase(https://github.com/spring-projects/spring-mvc-showcase),它当前的版本使用的是4.1.0,以后会有所变动,为了使项目能够运行,请以它更新的配置为参考。
我用的IDE是IntelliJ IDEA13,我个人认为比Eclipse好用很多,是付费的,很贵!
项目结构
使用maven构建项目,项目结构如下:
在Controller层的测试不需要写单独的Spring config,可以直接使用src/main/java中的.xml
这里记录一下,Spring Mvc context的配置策略:
好多的小伙伴都会在一个文件(e.g spring-mvc.xml)中配置很多的东西,来看看showcase中web的配置结构
- WEB-INF
- web.xml (文件)
spring (文件夹)
- root-context.xml (文件,放置能够被servlet和filter共享使用的资源)
- appServlet (目录)
- controllers.xml(文件,与Controller相关的配置)
- servlet-context.xml (文件,放置有servlet使用的资源)
Spring mvc是对Servlet的包装,使其能够结构化,流程化。
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"> <!-- The definition of the Root Spring Container shared by all Servlets and Filters --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring/root-context.xml</param-value> </context-param> <!-- Creates the Spring Container shared by all Servlets and Filters --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <filter> <filter-name>csrfFilter</filter-name> <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> <async-supported>true</async-supported> </filter> <filter-mapping> <filter-name>csrfFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- Processes application requests --> <servlet> <servlet-name>appServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> <async-supported>true</async-supported> </servlet> <servlet-mapping> <servlet-name>appServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- Disables Servlet Container welcome file handling. Needed for compatibility with Servlet 3.0 and Tomcat 7.0 --> <welcome-file-list> <welcome-file></welcome-file> </welcome-file-list> </web-app>可以看到分开配置,使得文件的作用更加的明了。
这部分的配置文件是来配置web context 的,项目中还有其他的module ,如DAO,Service,他们对应的applicationContext文件会被放在src/main/resource目录下。
完善的单元测试当然还有service的单元测试,这里就不说了,但是Controller的单元测试还需要调用service和DAO,要注意Service和DAO的applicationContext的引入。
Controller 单元测试
在测试类中包含这三个注释,看起表面意思不难理解他们的作用,主要理解ContextConfiguration的使用。
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration //默认是src/main/webapp
@ContextConfiguration("file:src/main/webapp/WEB-INF/spring/appServlet/servlet-context.xml")
注意:这里的@ContextConfiguration只解析了servlet-context.xml,如果项目中还存在其他模块的applicationContext,也需要把他们引进来否则得到的Service就是null的。
例如
@ContextConfiguration({
"file:src/main/webapp/WEB-INF/spring/appServlet/servlet-context.xml",
“classpath*: springxml/**.xml”
})
在加上其他的一点代码就可以完成一个Controller的单元测试,下面是一个例子,更多例子请参考showcase中的内容。
package pairwinter.spring.mvc.controller.test; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.samples.mvc.AbstractContextControllerTests; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.web.servlet.MockMvc; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration({ "file:src/main/webapp/WEB-INF/spring/appServlet/servlet-context.xml", “classpath*: springxml/**.xml” }) public class ControllerTests{ @Autowired private WebApplicationContext wac; private MockMvc mockMvc; @Before public void setup() throws Exception { this.mockMvc = webAppContextSetup(this.wac).build(); } @Test public void controllerExceptionHandler() throws Exception { this.mockMvc.perform(get("/test")) .andExpect(status().isOk()); } }
Spring MVC Controller 单元测试的更多相关文章
- 关于Spring MVC Controller 层的单元测试
关于Spring MVC Controller 层的单元测试 测试准备工作: 1.搭建测试Web环境 2.注入Controller 类 3.编写测试数据 测试数据的文件名一定要与测试类的文件名相同,比 ...
- Spring MVC Controller中解析GET方式的中文参数会乱码的问题(tomcat如何解码)
Spring MVC Controller中解析GET方式的中文参数会乱码的问题 问题描述 在工作上使用突然出现从get获取中文参数乱码(新装机器,tomcat重新下载和配置),查了半天终于找到解决办 ...
- 转:【Spring MVC Controller单例陷阱】
http://lavasoft.blog.51cto.com/62575/1394669/ Spring MVC Controller默认是单例的: 单例的原因有二:1.为了性能.2.不需要多例. 1 ...
- Spring MVC Controller单例陷阱
原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 .作者信息和本声明.否则将追究法律责任.http://lavasoft.blog.51cto.com/62575/1394669 Spr ...
- Spring MVC Controller中GET方式传过来的中文参数会乱码的问题
Spring MVC controller 这样写法通常意味着访问该请求,GET和POST请求都行,可是经常会遇到,如果碰到参数是中文的,post请求可以,get请求过来就是乱码.如果强行对参数进行了 ...
- Spring MVC Controller与jquery ajax请求处理json
在用 spring mvc 写应用的时候发现jquery传递的[json数组对象]参数后台接收不到,多订单的处理,ajax请求: "}]}]} $.ajax({ url : url, typ ...
- spring mvc controller中获取request head内容
spring mvc controller中获取request head内容: @RequestMapping("/{mlid}/{ptn}/{name}") public Str ...
- Posting JSON to Spring MVC Controller
Spring MVC can be setup to automatically bind incoming JSON string into a Java object. Firstly, ensu ...
- 前台JSON字符串,spring mvc controller也接收字符串
前台JSON字符串,spring mvc controller也接收字符串 前台: $.post(url, { data : JSON.stringify(obj) }, function(data) ...
随机推荐
- PHP设计模式笔记九:装饰器模式 -- Rango韩老师 http://www.imooc.com/learn/236
装饰器模式(Decorator) 概述 1.装饰器模式可以动态地添加修改类的功能 2.一个类提供了一项功能,如果要在修改并添加额外的功能,传统的编程模式,需要写一个子类继承它,并重新实现类的方法 3. ...
- Visual Studio 2010 中的 Web 开发
概述 Microsoft Visual Studio 2010 为 ASP.NET Web 应用程序的开发提供非常多新的功能.这些新功能旨在帮助开发者高速方便地创建和部署质量高且功能全的 Web 应用 ...
- Linux文件 I/O 介绍
Linux文件 I/O 介绍 1. Linux系统调用 Linux系统调用(system call)是指操作系统提供给用户程序的一组"特殊接口",用户程序可以通过这组"特 ...
- CentOS7--DNS处理模块DnsPython的简单使用
初步了解: DnsPython是Python实现的一个DNS工具包,支持几乎所有的记录类型. 安装: # wget http://www.dnspython.org/kits/1.9.4/dnspyt ...
- 掌握jQuery插件开发,这篇文章就够了
---恢复内容开始--- 在实际开发工作中,总会碰到像滚动,分页,日历等展示效果的业务需求,对于接触过jQuery以及数据jQuery使用的人来说,首先想到的肯定是寻找现有的jQuery插件来满足形影 ...
- C# byte[]与char[]、string与char[]、byte[] 与 string 互转
1. byte array -> char array Byte[] b=new byte[5]{0x01,0x02,0x03,0x04,0x05}; Char[] c=Encoding.AS ...
- Code First 数据注释--InverseProperty 和 ForeignKey
ForeignKey 按照约定在Post类中看到BlogId属性,会认为是Blog类的外键,但是在Blog类中并没有BlogId属性,解决方法是,在 Post 中创建一个导航属性,并使用 Foreig ...
- Java数据结构漫谈-ArrayList
ArrayList是一个基于数组实现的链表(List),这一点可以从源码中看出: transient Object[] elementData; // non-private to simplify ...
- 图片拉伸(有保护区域) resizableImageWithCapInsets
在仿写QQ会话的时候背景蓝色图片是拉伸而来,但是有些地方是受保护的不能拉伸 所以定义了下面的工具类中的一个方法,专门拉伸图片 UIImageResizingModeStretch:拉伸模式,通过拉伸U ...
- C# Winform中DataGridView的DataGridViewCheckBoxColumn CheckBox选中判断
1.DataGridViewCheckBoxColumn CheckBox是否选中 在判断DataGridView中CheckBox选中列的时候,用DataGridViewRow.Cells[0].F ...