如何在springMVC 中对REST服务使用mockmvc 做测试
- junit 必须使用4.9以上
- 同时您的框架必须是用spring mvc
- spring 3.2以上才完美支持

- import org.junit.runner.RunWith;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.test.context.ContextConfiguration;
- import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
- import org.springframework.test.context.web.WebAppConfiguration;
- import org.springframework.web.context.WebApplicationContext;
- @WebAppConfiguration
- @ContextConfiguration (locations = { "classpath:applicationContext.xml" ,
- "classpath:xxxx-servlet.xml" })
- public class AbstractContextControllerTests {
- @Autowired
- protected WebApplicationContext wac;
- }
- 子类:
- 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.junit4.SpringJUnit4ClassRunner;
- import org.springframework.test.web.servlet.MockMvc;
- import org.springframework.test.web.servlet.setup.MockMvcBuilders;
- import com.conlect.oatos.dto.status.RESTurl;
- import com.qycloud.oatos.server.service.PersonalDiskService;
- //这个必须使用junit4.9以上才有。
- @RunWith (SpringJUnit4ClassRunner. class )
- public class PersonalDiskMockTests extends AbstractContextControllerTests {
- private static String URI = RESTurl.searchPersonalFile;
- private MockMvc mockMvc;
- private String json = "{\"entId\":1234,\"userId\":1235,\"key\":\"new\"}" ;
- @Autowired
- private PersonalDiskService personalDiskService;
- @Before
- public void setup() {
- //this.mockMvc = webAppContextSetup(this.wac).alwaysExpect(status().isOk()).build();
- this .mockMvc = MockMvcBuilders.standaloneSetup(personalDiskService).build();
- }
- @Test
- public void readJson() throws Exception {
- this .mockMvc.perform(
- post(URI, "json" ).characterEncoding( "UTF-8" )
- .contentType(MediaType.APPLICATION_JSON)
- .content(json.getBytes()))
- .andExpect(content().string( "Read from JSON: JavaBean {foo=[bar], fruit=[apple]}" )
- );
- }
- package com.qycloud.oatos.server.test.mockmvcTest;
- import static org.junit.Assert.fail;
- import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
- import java.io.UnsupportedEncodingException;
- import java.lang.reflect.Field;
- import org.springframework.http.MediaType;
- import org.springframework.test.web.servlet.MockMvc;
- import com.conlect.oatos.dto.status.CommConstants;
- import com.conlect.oatos.dto.status.ErrorType;
- import com.conlect.oatos.http.PojoMapper;
- public class MockUtil {
- /**
- * mock
- *
- * @param uri
- * @param json
- * @return
- * @throws UnsupportedEncodingException
- * @throws Exception
- */
- public static String mock(MockMvc mvc, String uri, String json)
- throws UnsupportedEncodingException, Exception {
- return mvc
- .perform(
- post(uri, "json" ).characterEncoding( "UTF-8" )
- .contentType(MediaType.APPLICATION_JSON)
- .content(json.getBytes())).andReturn()
- .getResponse().getContentAsString();
- }
- /**
- *
- * @param re 返回值
- * @param object 要转换的对象
- * @param testName 当前测试的对象
- */
- public static <T> void check(String re, Class<T> object,String testName) {
- System.out.println(re);
- if (ErrorType.error500.toString().equals(re)) {
- System.out.println( "-----该接口测试失败:-----"
- + testName);
- fail(re);
- } else if (CommConstants.OK_MARK.toString().equals(re)) {
- System.out.println( "-----该接口测试成功:-----"
- + testName);
- } else {
- System.out.println( "-----re----- :" +re);
- }
- if (object != null ) {
- if (re.contains( ":" )) {
- try {
- T t = PojoMapper.fromJsonAsObject(re, object);
- System.out.println( "-----该接口测试成功:-----"
- + testName);
- } catch (Exception e) {
- System.out.println( "-----该接口测试失败:-----"
- + testName);
- fail(e.getMessage());
- }
- }
- }
- }
- /**
- * 初始化版本信息。每次调用测试用力之前首先更新版本信息
- * @param mockMvc
- * @param url
- * @param fileId
- * @param class1
- * @return
- * @throws UnsupportedEncodingException
- * @throws Exception
- */
- public static <T> Long updateVersion(MockMvc mockMvc, String url,
- Long fileId, Class<T> class1) throws UnsupportedEncodingException, Exception {
- String re = mock(mockMvc, url, fileId+ "" );
- T dto = PojoMapper.fromJsonAsObject(re, class1);
- Long version = Long.parseLong(dto.getClass().getMethod( "getVersion" ).invoke(dto).toString());
- System.out.println( "version = " +version);
- return version;
- }
- }
使用如下:
- @RunWith (SpringJUnit4ClassRunner. class )
- public class PersonalDiskMockTests extends AbstractContextControllerTests {
- private MockMvc mockMvc;
- private static Long entId = 1234L;
- private static Long adminId = 1235L;
- @Autowired
- private PersonalDiskService personalDiskService;
- @Before
- public void setup() {
- this .mockMvc = MockMvcBuilders.standaloneSetup(personalDiskService)
- .build();
- }
- /***
- * pass
- * 全局搜索企业文件
- *
- * @throws Exception
- */
- @Test
- public void searchPersonalFile() throws Exception {
- SearchFileParamDTO sf = new SearchFileParamDTO();
- sf.setEntId(entId);
- sf.setKey( "li" );
- sf.setUserId(adminId);
- String json = PojoMapper.toJson(sf);
- String re = MockUtil.mock( this .mockMvc, RESTurl.searchPersonalFile,
- json);
- MockUtil.check(re, SearchPersonalFilesDTO. class , "searchPersonalFile" );
- }
- }
当然@setup里面是每个@test执行时都会执行一次的,所以有些需要每次都实例化的参数可以放进来
- @Autowired
- private ShareDiskService shareDiskService;
- @Before
- public void setup() {
- this .mockMvc = MockMvcBuilders.standaloneSetup(shareDiskService)
- .build();
- try {
- initDatas();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- private void initDatas() throws UnsupportedEncodingException, Exception {
- FileIdVersion = MockUtil.updateVersion(mockMvc,RESTurl.getShareFileById,FileId,ShareFileDTO. class );
- File2IdVersion = MockUtil.updateVersion(mockMvc,RESTurl.getShareFileById,File2Id,ShareFileDTO. class );
- oldPicFolderVersion = MockUtil.updateVersion(mockMvc,RESTurl.getShareFolderById,oldPicFolderId,ShareFolderDTO. class );
- }
- 以上是我摘抄别人的,以下是我在公司用的写法
测试类:
package cn.com.mcd;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;import org.codehaus.jackson.map.ObjectMapper;
import org.junit.Assert;
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.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;import cn.com.mcd.common.ResultModel;
import cn.com.mcd.controller.StoreLocalPmController;
import cn.com.mcd.model.StoreLocalPm;@RunWith(SpringJUnit4ClassRunner.class)
public class TestStoreLocalPm extends BaseControllerTest{
//@Resource
//private StoreLocalPmService storeLocalPmService;
@Autowired
private StoreLocalPmController storeLocalPmController;
private MockMvc mockMvc;
@Before
public void setup() {
//this.mockMvc = webAppContextSetup(this.wac).alwaysExpect(status().isOk()).build();
this.mockMvc = MockMvcBuilders.standaloneSetup(storeLocalPmController).build();
}
/**
* 根据条件查询列表
*/
//@Test
public void selectStoreLocalPmList() {
StoreLocalPm storeLocalPm=new StoreLocalPm();
Long id=1L;
storeLocalPm.setId(id);//餐厅编号
storeLocalPm.setStoreName("");//餐厅名称
storeLocalPm.setAuditStatus("");//审核状态
ResultModel resultModel=storeLocalPmController.selectStoreLocalPmList(null,storeLocalPm);
System.out.print("test.resultModel="+resultModel.getResultCode()+"\n"+resultModel.getResultMsg()+"\n"+resultModel.getResultData());
}
/**
* 根据id查询详情
* @throws Exception
*/
@Test
public void selectByPrimaryKey() throws Exception {
String url = "/storeLocalPm/selectByPrimaryKey";
StoreLocalPm storeLocalPm =new StoreLocalPm();
storeLocalPm.setId(1L);
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(storeLocalPm);
MvcResult result = (MvcResult) mockMvc.perform(post(url)
.contentType(MediaType.APPLICATION_JSON)
.content(json)
.param("epsToken", "token")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andDo(MockMvcResultHandlers.print())
.andReturn();
System.out.println("----------"+result.getResponse().getStatus());
System.out.println("----------"+result.getResponse().getContentAsString());
//Assert.assertEquals(200, result.getResponse().getStatus());
//Assert.assertNotNull(result.getResponse().getContentAsString());
//Long id=1L;
//ResultModel resultModel=storeLocalPmController.selectByPrimaryKey(id);
//System.out.print("test.resultModel="+resultModel.getResultCode()+"\n"+
//resultModel.getResultMsg()+"\n"+resultModel.getResultData());
}
}- cotroller
package cn.com.mcd.controller;
import java.util.List;
import javax.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;import cn.com.mcd.common.ResultModel;
import cn.com.mcd.model.KitchenEquipmentPrice;
import cn.com.mcd.model.StoreLocalPm;
import cn.com.mcd.service.StoreLocalPmService;
import cn.com.mcd.util.Constants;
import cn.com.mcd.util.PagesPojo;@Controller
@RequestMapping("/storeLocalPm")
public class StoreLocalPmController {
private static final long serialVersionUID = 4515788554984036250L;
private static final Logger log = LoggerFactory.getLogger(StoreLocalPmController.class);
@Resource
private StoreLocalPmService storeLocalPmService;
/**
* query detail by id
* @param id
* @return
*/
@RequestMapping(value = "/selectByPrimaryKey", method = RequestMethod.POST)
@ResponseBody
public ResultModel selectByPrimaryKey(@RequestBody StoreLocalPm storeLocalPm) {
log.info(this.getClass().getName()+".selectByPrimaryKey.start.storeLocalPm="+storeLocalPm);
ResultModel resultModel = new ResultModel();
try{
storeLocalPm=storeLocalPmService.selectByPrimaryKey(storeLocalPm.getId());
log.info(this.getClass().getName()+".selectByPrimaryKey.success.storeLocalPm="+storeLocalPm);
resultModel.setResultCode(Constants.SERVICE_SUCCESS_CODE);
resultModel.setResultMsg(Constants.DATA_BASE_SEARCH_SUCCESS_MSG);
resultModel.setResultData(storeLocalPm);
}catch(Exception e){
resultModel.setResultCode(Constants.SERVICE_ERROR_CODE);
resultModel.setResultMsg(Constants.DATA_BASE_SEARCH_ERROR_MSG);
}
log.info(this.getClass().getName()+".selectByPrimaryKey.end.resultModel="+resultModel);
return resultModel;
}
/**
* query list by param
* @param id
* @return
*/
@RequestMapping(value = "/selectStoreLocalPmList", method = RequestMethod.GET)
@ResponseBody
public ResultModel selectStoreLocalPmList(@ModelAttribute PagesPojo<StoreLocalPm> page,StoreLocalPm storeLocalPm) {
log.info(this.getClass().getName()+".selectStoreLocalPmList.start.page="+page);
ResultModel result = new ResultModel();
try{
int count = storeLocalPmService.countAll(storeLocalPm);
page.setTotalRow(count);
List<StoreLocalPm> list = storeLocalPmService.selectStoreLocalPmList(page);
page.setPages(list);
result.setResultCode(Constants.SERVICE_SUCCESS_CODE);
result.setResultMsg(Constants.DATA_BASE_SEARCH_SUCCESS_MSG);
result.setResultData(page);
}catch(Exception e){
result.setResultCode(Constants.SERVICE_ERROR_CODE);
result.setResultMsg(Constants.DATA_BASE_SEARCH_ERROR_MSG);
}
log.info(this.getClass().getName()+".selectStoreLocalPmList.end.result="+result);
return result;
}
int deleteByPrimaryKey(Long id){
return 0;
}int insert(StoreLocalPm record) {
return 0;
}int insertSelective(StoreLocalPm record){
return 0;
}int updateByPrimaryKeySelective(StoreLocalPm record) {
return 0;
}int updateByPrimaryKey(StoreLocalPm record) {
return 0;
}
}
如何在springMVC 中对REST服务使用mockmvc 做测试的更多相关文章
- 如何在SpringMVC中使用REST风格的url
如何在SpringMVC中使用REST风格的url 1.url写法: get:/restUrl/{id} post:/restUrl delete:/restUrl/{id} put:/restUrl ...
- 如何在ubuntu中启用SSH服务
如何在ubuntu14.04 中启用SSH服务 开篇科普: SSH 为 Secure Shell 的缩写,由 IETF 的网络工作小组(Network Working Group)所制定:SSH 为 ...
- 如何在Ruby中编写微服务?
[编者按]本文作者为 Pierpaolo Frasa,文章通过详细的案例,介绍了在Ruby中编写微服务时所需注意的方方面面.系国内 ITOM 管理平台 OneAPM 编译呈现. 最近,大家都认为应当采 ...
- 如何在IIS中设置HTTPS服务
文章:https://support.microsoft.com/en-us/help/324069/how-to-set-up-an-https-service-in-iis 在这个任务中 摘要 为 ...
- 如何在SpringMVC中获取request对象
1.注解法 @Autowired private HttpServletRequest request; <listener> <listener-class> org.spr ...
- 如何在BPM中使用REST服务(1):通过程序访问网页内容
这篇文章主要描述如何通过程序来访问网页内容,这是访问REST服务的基础. 在Java中,我们可以使用HttpUrlConnection类来实现,代码如下. package http.base; imp ...
- 如何在 IIS 中设置 HTTPS 服务
Windows Server2008.IIS7启用CA认证及证书制作完整过程 这篇文章介绍了如何安装证书申请工具: 如何在iis创建证书申请: 如何使用iis申请证书生成的txt文件,在工具中开始申请 ...
- 技术干货丨如何在VIPKID中构建MQ服务
小结: 1. https://mp.weixin.qq.com/s/FQ-DKvQZSP061kqG_qeRjA 文 |李伟 VIPKID数据中间件架构师 交流微信 | datapipeline201 ...
- 如何在Linux中关闭apache服务(转)
??? 最近在写一个简单的http服务器,调试的时候发现apache服务器也在机器上跑着,所以得先把apache关掉.当时装apache的时候就是用了普通的sudo get,也不知道装到哪儿了.到网上 ...
随机推荐
- Java中String,StringBuffer与StringBuilder的差别
String 字符串常量: StringBuffer 字符串变量〈缓冲区〉(线程安全): StringBuilder 字符串变量〈缓冲区〉(非线程安全): 简要的说, String 类型和 Strin ...
- 【Java EE 学习 17 上】【dbutils和回调函数】
一.dbutils的核心就是回调函数,可以说如果没有回调函数的思想,dbutils是不可能被开发出来的. 对于dbutils中的QuryRunner类,向该类的query方法提供不同的参数,可以得到不 ...
- android 教程实例系列
用户界面部分学起来还真是无处下手哇,总不能一个控件发一篇文吧,略有点费时间啊...这个难道不是边用边学才给力吗..所以我打算从最实用的Button开始下手. 先贴几个链接,好东西: android用户 ...
- threadid=1: thread exiting with uncaught exception (group=0xb2a86d70)
这个错误是程序运行成功,但是一在虚拟机上运行就报“停止运行了”,如图: 然后我们查看一个日志信息: 查了好久,终于 搞好了,原因是安卓目标SDK版本太高了,我这里创建好默认是这样的如图: 只要把21改 ...
- 创建WSDL项目
WSDL文件是测试基于soap的服务,他们定义实际暴露服务和要求SoapUI生成测试,要求信息,验证和MockServices. SoapUI支持最广泛使用的1.1版本的WSDL和SOAP 1.1和1 ...
- php递归获取顶级父类id
php递归获取顶级父类id function get_top_parentid($id){ $r = M('navclass')->where('id = '.$id)->field('i ...
- linux 内核cache
写驱动总会碰到和cache相关的东西 记录下用到的接口: 驱动中用的内存地址一般为内核地址,用户调用驱动接口时,有时候会把自己申请的地址赋给驱动,此时用户kmalloc得到内核地址, 再用mmap获得 ...
- ios 实现自定义状态栏StatusBar 和 导航栏navigationBar 的状态和颜色
很多app中可以看到不同与导航栏的状态栏的颜色,他妈的真绕嘴. 一.更改状态栏颜色 (StatusBar) 就是比如导航栏是红色的状态栏是绿色的. 要实现这样的效果其实很简单,就是添加一个背景view ...
- Android底部菜单的实现
前言:以前制作菜单使用TabHost,但是android 3.0以上就被废弃了,google已经不建议使这个类了.ActionBar也是菜单,不过在头部,算是导航了 ===本文就介绍怎么制作底部菜单= ...
- Jingle 相关问题
1. //page模板默认的相对位置,主要用于开发hybrid应用,实现page的自动装载 basePagePath : 'html/'. 所以所有的section 要放在html文件下面才行