简介

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. 2015第22周六Java反射、泛型、容器简介

    Java的反射非常强大,传递class, 可以动态的生成该类.取得这个类的所有信息,包括里面的属性.方法以及构造函数等,甚至可以取得其父类或父接口里面的内容. obj.getClass().getDe ...

  2. 黑马程序员_Java面向对象_包

    7.包 7.1包(package) 对类文件进行分类管理. 给类提供多层命名空间. 写在程序文件的第一行. 类名的全称是:包名.类名. 包也是一种封装形式. 利用命令行自动生成文件夹格式:D:\jav ...

  3. mavne install 报错org.apache.maven.surefire.util.SurefireReflectionException: java.lang.reflect.InvocationTargetException

    maven install 报错 org.apache.maven.surefire.util.SurefireReflectionException: java.lang.reflect.Invoc ...

  4. 解决selenium 启动ie浏览器报错:Unexpected error launching Internet Explorer. Protected Mode settings are not the same for all zones

    启动ie代码: System.setProperty("webdriver.ie.driver", "bin/IEDriverServer.exe"); Web ...

  5. python 标准库基础学习之开发工具部分1学习

    #2个标准库模块放一起学习,这样减少占用地方和空间#标准库之compileall字节编译源文件import compileall,re,sys#作用是查找到python文件,并把它们编译成字节码表示, ...

  6. java如何从方法返回多个值

    本文介绍三个方法,使java方法返回多个值. 方法1:使用集合类 方法2:使用封装对象 方法3:使用引用传递 示例代码如下: import java.util.HashMap; import java ...

  7. Windows系统下nodejs安装及配置

    关于nodejs中文站,眼下活跃度最好的知识站应该是http://www.cnodejs.org/ ,而http://cnodejs.org/则活跃度较低.Express.js是nodejs的一个MV ...

  8. Leetcode_num3_Same Tree

    题目: Given two binary trees, write a function to check if they are equal or not. Two binary trees are ...

  9. FileZilla简单介绍及运用

    一.FileZilla简介 FileZilla是一款免费开源的FTP客户端软件,并且还提供了服务器版本.虽然它是免费软件,可性能却一点也不含糊,比起那些共享软件来有过之而无不及,具备大多数的FTP软件 ...

  10. 用JS的for循环打印九九乘法表

    需要使用两个for循环嵌套,代码如下: <!DOCTYPE html> <html lang="en"> <head> <meta cha ...