简介

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 单元测试的更多相关文章

  1. 关于Spring MVC Controller 层的单元测试

    关于Spring MVC Controller 层的单元测试 测试准备工作: 1.搭建测试Web环境 2.注入Controller 类 3.编写测试数据 测试数据的文件名一定要与测试类的文件名相同,比 ...

  2. Spring MVC Controller中解析GET方式的中文参数会乱码的问题(tomcat如何解码)

    Spring MVC Controller中解析GET方式的中文参数会乱码的问题 问题描述 在工作上使用突然出现从get获取中文参数乱码(新装机器,tomcat重新下载和配置),查了半天终于找到解决办 ...

  3. 转:【Spring MVC Controller单例陷阱】

    http://lavasoft.blog.51cto.com/62575/1394669/ Spring MVC Controller默认是单例的: 单例的原因有二:1.为了性能.2.不需要多例. 1 ...

  4. Spring MVC Controller单例陷阱

    原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 .作者信息和本声明.否则将追究法律责任.http://lavasoft.blog.51cto.com/62575/1394669 Spr ...

  5. Spring MVC Controller中GET方式传过来的中文参数会乱码的问题

    Spring MVC controller 这样写法通常意味着访问该请求,GET和POST请求都行,可是经常会遇到,如果碰到参数是中文的,post请求可以,get请求过来就是乱码.如果强行对参数进行了 ...

  6. Spring MVC Controller与jquery ajax请求处理json

    在用 spring mvc 写应用的时候发现jquery传递的[json数组对象]参数后台接收不到,多订单的处理,ajax请求: "}]}]} $.ajax({ url : url, typ ...

  7. spring mvc controller中获取request head内容

    spring mvc controller中获取request head内容: @RequestMapping("/{mlid}/{ptn}/{name}") public Str ...

  8. Posting JSON to Spring MVC Controller

    Spring MVC can be setup to automatically bind incoming JSON string into a Java object. Firstly, ensu ...

  9. 前台JSON字符串,spring mvc controller也接收字符串

    前台JSON字符串,spring mvc controller也接收字符串 前台: $.post(url, { data : JSON.stringify(obj) }, function(data) ...

随机推荐

  1. 哲学家用餐问题的几个解法(c语言实现)

    参考资料: 1.维基百科:哲学家用餐问题 2.Windows的多线程编程

  2. hdu4641-K-string(后缀自动机)

    Problem Description Given a string S. K-string is the sub-string of S and it appear in the S at leas ...

  3. global.asax?app.config?webconfig??

    一.Global.asax 1.global.asax是什么? 一个文本文件,至于它包含写什么内容?顾名思义,global 肯定是掌管一个应用程序(application)的全局性的东西,例如应用程序 ...

  4. phpcms:六、频道页(category.html)

    1.当前栏目的ID:{$catid}标题样式:{title_style($v[style])}(在添加内容或编辑内容的时候,标题右边 有一个选择颜色的块).{str_cut(strip_tags($v ...

  5. 上传图片代码(chuantouxiang.php+touxiangchuli.php)

    <body> <form action="touxiangchuli.php" method="post" enctype="mul ...

  6. MyBatis初学者配置

    小配置 <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC &qu ...

  7. css中的边框样式

    在盒子模型中,盒子的边框是其重要的样式,通过边框我们可以很方便地看出盒子的长宽以及大小.边框的特性可以通过边框线,边框的宽度及颜色来呈现. 1,边框线 边框线指的是边框线条的样式,包括实线,虚线,点划 ...

  8. swing入门例子

    // a simple exmple that can show the basis of swing------------------------------------------------- ...

  9. playbin2 成员

    1. playbin2   struct _GstPlayBin {   GstPipeline parent;   GMutex *lock; GstSourceGroup groups[2]; G ...

  10. AVT Vimba与OpenCV环境配置

    近来,由于项目需求,需要使用AVT的一款相机采集图像并进行相应的算法处理.环境的配置过程较为复杂,特此记录,以做备忘.也给有需要的小伙伴们一些key point的分享. 搭建环境:Windows7 + ...