关于spring MVC单元测试常规的方法则是启动WEB服务器,测试出错 ,停掉WEB 改代码,重启WEB,测试,大量的时间都浪费在WEB服务器的启动上,下面介绍个实用的方法,spring
MVC单元测试.

package com.spring;





import java.io.FileNotFoundException;

import java.io.IOException;

import java.util.ArrayList;

import java.util.List;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;





import org.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.http.MediaType;

import org.springframework.stereotype.Controller;

import org.springframework.ui.Model;

import org.springframework.web.bind.annotation.PathVariable;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.bind.annotation.ResponseBody;

import org.springframework.web.context.ContextLoader;

import org.springframework.web.context.WebApplicationContext;

import org.springframework.web.context.support.WebApplicationContextUtils;

import org.springframework.web.servlet.ModelAndView;





@Controller

@RequestMapping(value = "/spring")

public class Action {





@Autowired

Teacher teacher;

// spring 支持restful的格式



@ResponseBody

@RequestMapping(value = "/rest/{ownerId}.do", method = RequestMethod.GET)

public String findOwner(@PathVariable String ownerId, Model model,

HttpServletResponse rep) throws IOException {

return ownerId;

}





@RequestMapping(value = "/test.do", method = RequestMethod.GET)

public String testa(Model model, HttpServletResponse rep)

throws IOException {

model.addAttribute("abc", "efd");

model.addAttribute(teacher);

return "a";

}





@ResponseBody

// 理论上可以@ResponseBody 支持直接返回teacher对象 但是3.2里有问题 我们还是老实返回字符串吧

@RequestMapping(value = "/testb.do", method = RequestMethod.GET)

public String testb(Model model, HttpServletResponse rep,

HttpServletRequest req, String ex) throws IOException {

// WEB中获得SPRING容器

WebApplicationContext wac = WebApplicationContextUtils

.getRequiredWebApplicationContext(req.getServletContext());

return new JSONObject(wac.getBean(Teacher.class)).toString();

}





@ResponseBody

@RequestMapping(value = "/post.do", method = RequestMethod.POST)

public String post(Model model, HttpServletResponse rep,

HttpServletRequest req, String ex) throws IOException {

return new JSONObject(req.getParameterMap()).toString();

}



}

单元测试代码

import java.awt.print.Printable;

import java.io.IOException;





import javax.servlet.http.HttpServletResponse;





import org.junit.Before;

import org.junit.Test;

import org.junit.runner.RunWith;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.http.MediaType;

import org.springframework.test.context.ContextConfiguration;

import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import org.springframework.test.context.web.WebAppConfiguration;

import org.springframework.test.web.servlet.MockMvc;

import org.springframework.test.web.servlet.ResultHandler;

import org.springframework.test.web.servlet.ResultMatcher;

import org.springframework.ui.Model;

import org.springframework.test.context.transaction.TransactionConfiguration;

import org.springframework.transaction.annotation.Transactional;

import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.*;

import static org.springframework.test.web.servlet.setup.MockMvcBuilders.*;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;

import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.context.WebApplicationContext;





@RunWith(SpringJUnit4ClassRunner.class)

@WebAppConfiguration

@ContextConfiguration(locations = { "classpath:applicationContext.xml" })

//当然 你可以声明一个事务管理 每个单元测试都进行事务回滚 无论成功与否

@TransactionConfiguration(defaultRollback = true)

//记得要在XML文件中声明事务哦~~~我是采用注解的方式

@Transactional

public class ExampleTests {





@Autowired

private WebApplicationContext wac;





private MockMvc mockMvc;





@Before

public void setup() {

// webAppContextSetup 注意上面的static import

// webAppContextSetup 构造的WEB容器可以添加fileter 但是不能添加listenCLASS

// WebApplicationContext context =

// ContextLoader.getCurrentWebApplicationContext();

// 如果控制器包含如上方法 则会报空指针

this.mockMvc = webAppContextSetup(this.wac).build();

}





@Test

        //有些单元测试你不希望回滚

        @Rollback(false)

public void ownerId() throws Exception {

mockMvc.perform((get("/spring/rest/4.do"))).andExpect(status().isOk())

.andDo(print());

}





@Test

public void test() throws Exception {

mockMvc.perform((get("/spring/test.do"))).andExpect(status().isOk())

.andDo(print())

.andExpect(model().attributeHasNoErrors("teacher"));

}





@Test

public void testb() throws Exception {

mockMvc.perform((get("/spring/testb.do"))).andExpect(status().isOk())

.andDo(print());

}





@Test

public void getAccount() throws Exception {

mockMvc.perform((post("/spring/post.do").param("abc", "def")))

.andExpect(status().isOk()).andDo(print());

}





}

Spring MVC学习总结(1)——Spring MVC单元测试的更多相关文章

  1. spring框架学习(三)junit单元测试

    spring框架学习(三)junit单元测试 单元测试不是头一次听说了,但只是听说从来没有用过.一个模块怎么测试呢,是不是得专门为一单元写一个测试程序,然后将测试单元代码拿过来测试? 我是这么想的.学 ...

  2. Spring Boot 学习1-创建Spring Boot应用

    如果使用Maven, 确保先安装好Maven再继续. 创建POM文件 在这里有两种方式: 继承Spring Boot parent的pom. 不继承. 继承Spring Boot pom 1 2 3 ...

  3. spring揭密学习笔记(1) --spring的由来

    1.spring起源于在EJB暴露出各种严重问题的情况应运而生. Spring是于2003年兴起的一个轻量级的Java开发框架, Spring倡导一切从实际出发,以实用的态度来选择适合当前开发场景的解 ...

  4. 【Spring Boot学习之四】Spring Boot事务管理

    环境 eclipse 4.7 jdk 1.8 Spring Boot 1.5.2 一.springboot整合事务事务分类:编程事务.声明事务(XML.注解),推荐使用注解方式,springboot默 ...

  5. 【Spring Boot学习之三】Spring Boot整合数据源

    环境 eclipse 4.7 jdk 1.8 Spring Boot 1.5.2 一.Spring Boot整合Spring JDBC 1.pom.xml <project xmlns=&quo ...

  6. spring boot学习(3) SpringBoot 之MVC 支持

    第一节:@RequestMapping 配置url 映射   第二节:@Controller 处理http 请求 转发到一个页面,以前是转发到jsp页面,现在使用freemarker: 在pom.xm ...

  7. 【Spring Boot学习之一】Spring Boot简介

    环境 Java1.8 Spring Boot 1.3.2 一.Spring Boot特点1.使用java运行项目,内置tomcat,无需外部容器:2.减少XML配置,使用properties文件和注解 ...

  8. Spring Boot 学习笔记 - 认识Spring Boot框架

    因各种原因,.NET前端工程师重新接触JAVA,真是向全栈的路上又迈出了无奈的一步. 下面正文: Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初 ...

  9. Spring基础学习(一)—初识Spring

    一.Spring的使用 1.导入jar包 2.编写实体类 Person.java public class Person{ private String name; public void say() ...

  10. Spring框架学习之--搭建spring框架

    此文介绍搭建一个最最简单的spring框架的步骤 一.创建一个maven项目 二.在pom.xml文件中添加依赖导入spring框架运行需要的相关jar包 注意:在引入jar包之后会出现org.jun ...

随机推荐

  1. Docker+Jenkins持续集成

    Docker+Jenkins持续集成 使用etcd+confd实现容器服务注册与发现   前面我们已经通过jenkins+docker搭建了基本的持续集成环境,实现了服务的自动构建和部署,但是,我们遇 ...

  2. es6 -- set 数据结构

    ES6 提供了新的数据结构 Set.它类似于数组,但是成员的值都是唯一的,没有重复的值. Set 本身是一个构造函数,用来生成 Set 数据结构. const s = new Set(); [2, 3 ...

  3. POJ 2374 线段树建图+Dijkstra

    题意: 思路: 线段树+Dijkstra(要堆优化的) 线段树要支持打标记 一个栅栏 拆成两个点 :左和右 新加一个栅栏的时候 看看左端点有没有被覆盖过 如果有的话 就分别从覆盖的那条线段的左右向当前 ...

  4. #学习笔记#——JavaScript 数组部分编程(七)

    24.柯里化 首先想解释一下,“柯里化”的意思, [在计算机科学中,柯里化(Currying)是把接受多个参数的函数变换成接受一个单一参数(最初函数的第一个参数)的函数,并且返回接受余下的参数且返回结 ...

  5. Cisco Works 2000 网络管理软件安装、配置全过程

    下面是在windows 2000 server 下安装ciscoworks 2000的过程.(附件中是标准avi格式文件,由于上传附件大小限制,更多内容见Sina播客) 浏览全部原创视频请见: htt ...

  6. 错误日志写入到本地磁盘(lock 队列)

    今天照常在b站上看看编程:看到有讲错误日志处理的,自己没写过日志,就看看了看: 主要是在讲的时候牵扯到了队列和lock的知识点:这方面知识自己了解的更少,那就记录一下.

  7. Kinect 开发 —— 手势识别(上)

    像点击(clicks)是GUI平台的核心,轻点(taps)是触摸平台的核心那样,手势(gestures)是Kinect应用程序的核心 关于手势的定义的中心在于手势能够用来交流,手势的意义在于讲述而不是 ...

  8. zabbix3.4.7搭建及邮件告警

    Zabbix3.4.7部署 系统环境:CentOs7.2 1.关闭selinux 1.1 [root@localhost ~]# setenforce 0 #临时关闭 1.2 [root@localh ...

  9. MyBatis学习总结(16)——Mybatis使用的几个建议

    1.Mapper层参数为Map,由Service层负责重载. Mapper由于机制的问题,不能重载,参数一般设置成Map,但这样会使参数变得模糊,如果想要使代码变得清晰,可以通过service层来实现 ...

  10. 爬虫爬数据时,post数据乱码解决的方法

    近期在写一个爬虫,目标站点是:http://zx.bjmemc.com.cn/.可能是为了防止被爬取数据,它给自身数据加了密. 用谷歌自带的抓包工具也不能捕获到数据. 于是下了Fiddler.     ...