示例代码

import com.alibaba.fastjson.JSONObject;
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.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; /**
* Created by hujunzheng on 2017/6/6.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:spring/spring-common.xml"})
@WebAppConfiguration
public class TestController { @Autowired
private WebApplicationContext webApplicationContext; private MockMvc mockMvc; @Before
public void setUp( ) {
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
} @Test
public void test() throws Exception { JSONObject params = new JSONObject();
params.put("userId", 123);
params.put("page", 1);
params.put("size", 1);
String responseString = mockMvc.perform(
MockMvcRequestBuilders.post("/wallet/records")
.accept(MediaType.ALL)
// .contentType(MediaType.APPLICATION_FORM_URLENCODED)
// .param("userId", "123")
.contentType(MediaType.APPLICATION_JSON)
.content(params.toJSONString())
)//.andExpect(MockMvcResultMatchers.status().isOk())
.andDo(print()) //打印出请求和相应的内容
.andReturn().getResponse().getContentAsString(); System.out.println(responseString);
} }

执行结果

MockHttpServletRequest:
HTTP Method = POST
Request URI = /wallet/records
Parameters = {}
Headers = {Accept=[*/*], Content-Type=[application/json]} Handler:
Type = com.beiquan.light.web.controller.WalletController
Method = public java.lang.String com.beiquan.light.web.controller.WalletController.records(com.beiquan.light.web.result.wallet.WalletRecordsReqForm,org.springframework.validation.BindingResult) Async:
Was async started = false
Async result = null Resolved Exception:
Type = null ModelAndView:
View name = null
View = null
Model = null FlashMap: MockHttpServletResponse:
Status = 200
Error message = null
Headers = {Content-Type=[text/plain;charset=UTF-8], Content-Length=[258], Accept-Charset=[big5, big5-hkscs, cesu-8, euc-jp, euc-kr, gb18030, gb2312, gbk, ibm-thai, ibm00858, ibm01140, ibm01141, ibm01142, ibm01143, ibm01144, ibm01145, ibm01146, ibm01147, ibm01148, ibm01149, ibm037, ibm1026, ibm1047, ibm273, ibm277, ibm278, ibm280, ibm284, ibm285, ibm290, ibm297, ibm420, ibm424, ibm437, ibm500, ibm775, ibm850, ibm852, ibm855, ibm857, ibm860, ibm861, ibm862, ibm863, ibm864, ibm865, ibm866, ibm868, ibm869, ibm870, ibm871, ibm918, iso-2022-cn, iso-2022-jp, iso-2022-jp-2, iso-2022-kr, iso-8859-1, iso-8859-13, iso-8859-15, iso-8859-2, iso-8859-3, iso-8859-4, iso-8859-5, iso-8859-6, iso-8859-7, iso-8859-8, iso-8859-9, jis_x0201, jis_x0212-1990, koi8-r, koi8-u, shift_jis, tis-620, us-ascii, utf-16, utf-16be, utf-16le, utf-32, utf-32be, utf-32le, utf-8, windows-1250, windows-1251, windows-1252, windows-1253, windows-1254, windows-1255, windows-1256, windows-1257, windows-1258, windows-31j, x-big5-hkscs-2001, x-big5-solaris, x-compound_text, x-euc-jp-linux, x-euc-tw, x-eucjp-open, x-ibm1006, x-ibm1025, x-ibm1046, x-ibm1097, x-ibm1098, x-ibm1112, x-ibm1122, x-ibm1123, x-ibm1124, x-ibm1166, x-ibm1364, x-ibm1381, x-ibm1383, x-ibm300, x-ibm33722, x-ibm737, x-ibm833, x-ibm834, x-ibm856, x-ibm874, x-ibm875, x-ibm921, x-ibm922, x-ibm930, x-ibm933, x-ibm935, x-ibm937, x-ibm939, x-ibm942, x-ibm942c, x-ibm943, x-ibm943c, x-ibm948, x-ibm949, x-ibm949c, x-ibm950, x-ibm964, x-ibm970, x-iscii91, x-iso-2022-cn-cns, x-iso-2022-cn-gb, x-iso-8859-11, x-jis0208, x-jisautodetect, x-johab, x-macarabic, x-maccentraleurope, x-maccroatian, x-maccyrillic, x-macdingbat, x-macgreek, x-machebrew, x-maciceland, x-macroman, x-macromania, x-macsymbol, x-macthai, x-macturkish, x-macukraine, x-ms932_0213, x-ms950-hkscs, x-ms950-hkscs-xp, x-mswin-936, x-pck, x-sjis_0213, x-utf-16le-bom, x-utf-32be-bom, x-utf-32le-bom, x-windows-50220, x-windows-50221, x-windows-874, x-windows-949, x-windows-950, x-windows-iso2022jp]}
Content type = text/plain;charset=UTF-8
Body = {"code":"SUCCESS","message":"成功","data":{"page":1,"size":1,"total":2,"list":[{"id":7,"walletId":1,"userId":123,"type":1,"value":1000.00,"origin":"cvs-哈哈","action":"test","desc":"","balance":1000.00,"payCode":"支付宝","createTime":1497006708000}]}}
Forwarded URL = null
Redirected URL = null
Cookies = []
{"code":"SUCCESS","message":"成功","data":{"page":1,"size":1,"total":2,"list":[{"id":7,"walletId":1,"userId":123,"type":1,"value":1000.00,"origin":"cvs-哈哈","action":"test","desc":"","balance":1000.00,"payCode":"支付宝","createTime":1497006708000}]}}

遇到问题

java.lang.NoSuchMethodError: javax.servlet.http.HttpServletRequest.isAsyncStarted() 

  servlet-api jar包版本的问题。我这里直接依赖上了tomcat中的library,解决该问题。

springmvc中使用MockMvc测试controller的更多相关文章

  1. springboot使用MockMvc测试controller

    通常,在我们平时开发项目时,如果想要输入URL对Controller进行测试,在代码编辑之后,需要重启服务器,建立http client进行测试.这样会使得测试变得很麻烦,比如,启动速度慢,测试验证不 ...

  2. 使用MockMvc测试controller

    之前我们测试controller的时候仅仅是作为一个pojo来进行简单的测试,spring3.2后我们可以按照控制器的方式来测试Spring MVC的controller了,这样的话在测试控制器的时候 ...

  3. spring-mvc springboot 使用MockMvc对controller进行测试

    网上基本都是参考官方的使用方式,使用了import static,个人感觉这种方式特别不好,代码提示性不友好.所以在此进行说明,也方便自己以后使用. 1. 引入spring-test相关jar包,sp ...

  4. springboot利用MockMvc测试controller控制器

    主要记录一下控制器的测试,service这些类测试相对简单些(可测试性强) API测试需求比较简单: ① 需要返回正确的http状态码 200 ② 需要返回json数据,并且不能返回未经捕获的系统异常 ...

  5. SpringMVC中url映射到Controller

    SpringMVC也是一种基于请求驱动的WEB框架,并且使用了前端控制器的设计模式.前端控制器就是DispatcherServlet控制器,只要满足web.xml文件中的[url-pattern]的规 ...

  6. SpringMVC中配置AOP拦截controller 失效

    来源:http://www.oschina.net/question/222929_124314 目测大部分同学的aop失效都是因为在springmvc的配置文件里面扫描了类,那么spring去扫描的 ...

  7. SpringMVC中的拦截器、过滤器的区别、处理异常

    1. SpringMVC中的拦截器(Interceptor) 1.1. 作用 拦截器是运行在DispatcherServlet之后,在每个Controller之前的,且运行结果可以选择放行或拦截! 除 ...

  8. 如何在springMVC 中对REST服务使用mockmvc 做测试

    如何在springMVC 中对REST服务使用mockmvc 做测试 博客分类: java 基础 springMVCmockMVC单元测试  spring 集成测试中对mock 的集成实在是太棒了!但 ...

  9. Spring MVC如何测试Controller(使用springmvc mock测试)

    在springmvc中一般的测试用例都是测试service层,今天我来演示下如何使用springmvc mock直接测试controller层代码. 1.什么是mock测试? mock测试就是在测试过 ...

随机推荐

  1. (转)Maven学习总结(一)——Maven入门 安装使用

    备注 转自: 孤傲苍狼 http://www.cnblogs.com/xdp-gacl/p/3498271.html 只为成功找方法,不为失败找借口! 1. Maven的基本概念 Maven(翻译为& ...

  2. spring的controller默认是单例还是多例

    转: spring的controller默认是单例还是多例 先看看spring的bean作用域有几种,分别有啥不同. spring bean作用域有以下5个: singleton:单例模式,当spri ...

  3. 安装【Jenkins】

    前言      jenkins的一款持续集成工具,      它可以做的事情很多,其中一个主要的功能就是简化部署流程          回想一下我们的发布流程:           1.本地把项目打包 ...

  4. bzoj千题计划204:bzoj2813: 奇妙的Fibonacci

    http://www.lydsy.com/JudgeOnline/problem.php?id=2813 若j能整除i,则f[j]能整除f[i] 题目就变成了求约数个数和.约数的平方和 http:// ...

  5. ASP.NET MVC学习笔记-----ControllerFactory

    上面这张图是asp.net mvc的工作流程图,我们可以看到当一个http请求来临时,首先需要经过路由系统,路由系统从中获取一些路由信息,然后ControllerFactory根据所得到的路由信息生成 ...

  6. 在html5 canvas的destination-atop属性的一些奇怪的问题

    最近在整理canvas的时候发现HTML5 Canvas开发详解一个奇怪的属性解释 目标图形是显示在画布上的位图 而原图形是指要回执在画布上的形状 w3school上面是这样说的 destinatio ...

  7. Spring Mvc Web 配置拦截规则与访问静态资源 (三)

    拦截规则配置 1. *.do <!-- Processes application requests --> <servlet> <servlet-name>app ...

  8. 大话C#中能使用foreach的集合的实现

    大家都知道foreach的语法:foreach(var item in items){ Console.Writeln(item);} 通过这样一个简单的语句,就能实现遍历集合items中的所有元素. ...

  9. C - Balanced Number HDU - 3709 (数位dp)

    题目链接:https://cn.vjudge.net/contest/278036#problem/C 题目大意:手首先是T组数据,然后每一次输入两个数l,r,求这个区间里面满足以某个数字为中心的两侧 ...

  10. MySQL 5.6 Replication 复制 FAQ

    原文请参照MySQL官方文档Reference Manual,版本5.6.10. 复制功能使得数据可以从一个MySQL数据库(master主库)复制到另一个或多个MySQL数据库(slave从库).缺 ...