简介

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());

}

}

最新文章

  1. AJAX大文件切割上传以及带进度条。
  2. [MetaHook] Load DTX texture to OpenGL
  3. C语言创建并使用lib
  4. ORA-3136报错
  5. AJAX最简单的原理以及应用
  6. php中date函数获取当前时间的时区误差解决办法
  7. Form类的KeyPreview属性
  8. span设置宽度有效无效问题
  9. eclipse的注释
  10. Android动画深入分析
  11. 【keras】用tensorboard监视CNN每一层的输出
  12. [Codeforces Round #438][Codeforces 868C. Qualification Rounds]
  13. T-SQL基础(三)之子查询与表表达式
  14. Spring 使用介绍(三)—— 资源
  15. C# 计算位置居中
  16. Python多进程库multiprocessing中进程池Pool类的使用[转]
  17. linux每日命令(11):cat命令
  18. PlayerPrefs Elite v1.4.3
  19. substitute 命令与 global 命令
  20. 微信小程序 --- loading提示框

热门文章

  1. "V租房"搭建微信租房平台,让租房人发起求租需求并接收合适房源回复,提高租房效率 | 36氪
  2. 用Nginx实现Session共享的均衡负载
  3. java对象在hibernate持久层的状态
  4. 分页标签:pager-taglib使用指南
  5. 5狐网教你从零基础做Firefox os 手机应用开发赚money
  6. hdu1047(模拟大量的循环添加)
  7. 6、Cocos2dx 3.0游戏开发找小三之游戏的基本概念
  8. android 中文件加密 解密 算法实战
  9. XMLHttpRequest取得响应
  10. WebApi2官网学习记录--HTTP Message Handlers