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

\u5982\u4f55\u5728springMVC \u4e2d\u5bf9REST\u670d\u52a1\u4f7f\u7528mockmvc \u505a\u6d4b\u8bd5

spring \u96c6\u6210\u6d4b\u8bd5\u4e2d \u5bf9mock \u7684\u96c6\u6210\u5b9e\u5728\u662f\u592a\u68d2\u4e86\uff01\u4f46\u662f\u4f7f\u7528\u8bf7\u6ce8\u610f\u4e00\u4e0b3\u4e2a\u6761\u4ef6\u3002

junit \u5fc5\u987b\u4f7f\u75284.9\u4ee5\u4e0a
\u540c\u65f6\u60a8\u7684\u6846\u67b6\u5fc5\u987b\u662f\u7528spring mvc
spring 3.2\u4ee5\u4e0a\u624d\u5b8c\u7f8e\u652f\u6301

\u76ee\u524d\u4f7f\u7528spring MVC \u53d6\u4ee3struts2 \u7684\u5f88\u591a\uff0cspring MVC \u7684\u5404\u79cd\u7075\u6d3b\u8ba9\u4eba\u65e0\u6bd4\u9500\u9b42\uff01\u6240\u4ee5\u4f7f\u7528spring MVC\u5427\uff01
\u4ee5\u524d\u5728\u5bf9\u63a5\u53e3\uff08\u4e3b\u8981\u662fjava\u670d\u52a1\u7aef\u63d0\u4f9b\u7684\u63a5\u53e3\uff08\u4e00\u822c\u662f\uff1awebService,restful\uff09\uff09\u8fdb\u884c\u6d4b\u8bd5\u7684\u4e2d \u4e00\u822c\u7528\u4ee5\u4e0b\u4fe9\u79cd\u65b9\u6cd5\u3002\u6d4b\u8bd5\u6d41\u7a0b\u5982\u56fe\uff1a


1 \u76f4\u63a5\u4f7f\u7528httpClient
\u8fd9\u65b9\u6cd5\u5404\u79cd\u9ebb\u70e6

2 \u4f7f\u7528Spring \u63d0\u4f9b\u7684RestTemplate
\u9519\u8bef\u4e0d\u597d\u8ddf\u8e2a\uff0c\u5fc5\u987b\u5f00\u7740\u670d\u52a1\u5668

\u4f7f\u7528mockMVC\u90fd\u4e0d\u662f\u95ee\u9898\u4e86\u770b\u4f7f\u7528\u5b9e\u4f8b\uff1a

\u4f7f\u7528\u4e8b\u4f8b\u5982\u4e0b\uff1a\u7236\u7c7b
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;

}

\u5b50\u7c7b\uff1a

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;

//\u8fd9\u4e2a\u5fc5\u987b\u4f7f\u7528junit4.9\u4ee5\u4e0a\u624d\u6709\u3002
@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]}")
);
}

\u4e0a\u9762\u662f\u7b80\u5355\u7684\u4f8b\u5b50\uff0c\u5b9e\u9645\u4f7f\u7528\u8d77\u6765\u53ef\u4ee5\u7a0d\u505a\u4fee\u6539\u3002\u8bb0\u5f97\u5bfc\u5165spring -test jar \u5305\u3002\u65e0\u9700\u989d\u5916\u914d\u7f6e\uff08\u662f\u4e0d\u662f\u5f88\u65b9\u4fbf\uff01\uff09
\u5f53\u7136\u548cjunit \u7684assert \u4e00\u8d77\u7528\u7684\u8bdd\u6548\u679c\u66f4\u597d\u3002\u4e0b\u9762\u8d34\u70b9\u4f8b\u5b50\u3002copy\u5c31\u80fd\u8dd1\u3002
Java\u4ee3\u7801
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 \u8fd4\u56de\u503c
* @param object \u8981\u8f6c\u6362\u7684\u5bf9\u8c61
* @param testName \u5f53\u524d\u6d4b\u8bd5\u7684\u5bf9\u8c61
*/
public static void check(String re, Class object,String testName) {
System.out.println(re);
if (ErrorType.error500.toString().equals(re)) {
System.out.println("-----\u8be5\u63a5\u53e3\u6d4b\u8bd5\u5931\u8d25\uff1a-----"
+ testName);
fail(re);
} else if (CommConstants.OK_MARK.toString().equals(re)) {
System.out.println("-----\u8be5\u63a5\u53e3\u6d4b\u8bd5\u6210\u529f\uff1a-----"
+ testName);
}else{
System.out.println("-----re----- :"+re);
}
if (object != null) {
if (re.contains(":")) {
try {
T t = PojoMapper.fromJsonAsObject(re, object);
System.out.println("-----\u8be5\u63a5\u53e3\u6d4b\u8bd5\u6210\u529f\uff1a-----"
+ testName);
} catch (Exception e) {
System.out.println("-----\u8be5\u63a5\u53e3\u6d4b\u8bd5\u5931\u8d25\uff1a-----"
+ testName);
fail(e.getMessage());
}
}
}

}


/**
* \u521d\u59cb\u5316\u7248\u672c\u4fe1\u606f\u3002\u6bcf\u6b21\u8c03\u7528\u6d4b\u8bd5\u7528\u529b\u4e4b\u524d\u9996\u5148\u66f4\u65b0\u7248\u672c\u4fe1\u606f
* @param mockMvc
* @param url
* @param fileId
* @param class1
* @return
* @throws UnsupportedEncodingException
* @throws Exception
*/
public static Long updateVersion(MockMvc mockMvc, String url,
Long fileId, Class 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;

}

}
\u4f7f\u7528\u5982\u4e0b\uff1a
Java\u4ee3\u7801
@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
* \u5168\u5c40\u641c\u7d22\u4f01\u4e1a\u6587\u4ef6
*
* @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");

}
\uff5d
\u5f53\u7136@setup\u91cc\u9762\u662f\u6bcf\u4e2a@test\u6267\u884c\u65f6\u90fd\u4f1a\u6267\u884c\u4e00\u6b21\u7684\uff0c\u6240\u4ee5\u6709\u4e9b\u9700\u8981\u6bcf\u6b21\u90fd\u5b9e\u4f8b\u5316\u7684\u53c2\u6570\u53ef\u4ee5\u653e\u8fdb\u6765
\u5982\u4e0b\uff1a
Java\u4ee3\u7801
@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);
}
ok\uff01\u57fa\u672c\u4f7f\u7528\u5927\u81f4\u5982\u6b64\uff0c\u4ee3\u7801\u6ca1\u6709\u4e9b\u6ce8\u91ca\uff0c\u4f46\u662f\u5f88\u7b80\u5355\uff0c\u770b\u61c2\u662f\u6ca1\u95ee\u9898\u7684\u3002\u6743\u5f53\u629b\u7816\u5f15\u7389\u3002\u5e0c\u671b\u5927\u5bb6\u52a0\u4ee5\u6307\u6b63\uff01

\u6211\u4eec\u5c31\u4ee5\u5982\u4e0b\u7f51\u7edc\u5546\u5e97\u7684Rest\u670d\u52a1\u4e3a\u4f8b\uff0c\u770b\u770b\u6211\u4eec\u901a\u8fc7Android\u5ba2\u6237\u7aef\u662f\u5982\u4f55\u8fdb\u884c\u8c03\u7528\u7684\uff08\u8fd9\u91cc\u53ea\u4ecb\u7ecd\u5982\u4f55\u53d1\u9001\u8bf7\u6c42\uff0c\u5e76\u83b7\u5f97\u670d\u52a1\u5668\u54cd\u5e94\uff09\u3002

Android\u7c7b\u5e93\u4e2d\u5df2\u7ecf\u4e3a\u6211\u4eec\u63d0\u4f9b\u4e86\u4e00\u5207\u6211\u4eec\u9700\u8981\u7684\u4e1c\u897f\u3002
Rest\u7684\u539f\u7406\u5c31\u662f\u5411\u4e00\u4e2a\u8d44\u6e90\u7684URI\u53d1\u9001GET\u3001POST\u3001PUT\u548cDELETE\u8fdb\u884c\u83b7\u53d6\u3001\u521b\u5efa\u3001\u4fdd\u5b58\u3001\u5220\u9664\u64cd\u4f5c\u3002

\u7b2c\u4e00\u6b65\u6211\u4eec\u770b\u770b\u5982\u4f55\u8bf7\u6c42\u83b7\u5f97\u6240\u6709\u5546\u54c1\u4fe1\u606f\uff1a
//\u521b\u5efa\u4e00\u4e2ahttp\u5ba2\u6237\u7aef
HttpClient client=new DefaultHttpClient();
//\u521b\u5efa\u4e00\u4e2aGET\u8bf7\u6c42
HttpGet httpGet=new HttpGet("http://www.store.com/products");
//\u5411\u670d\u52a1\u5668\u53d1\u9001\u8bf7\u6c42\u5e76\u83b7\u53d6\u670d\u52a1\u5668\u8fd4\u56de\u7684\u7ed3\u679c
HttpResponse response=client.execute(httpGet);
//\u8fd4\u56de\u7684\u7ed3\u679c\u53ef\u80fd\u653e\u5230InputStream\uff0chttp Header\u4e2d\u7b49\u3002
InputStream inputStream=response.getEntity().getContent();
Header[] headers=response.getAllHeaders();
\u901a\u8fc7\u89e3\u6790\u670d\u52a1\u5668\u8fd4\u56de\u7684\u6d41\uff0c\u6211\u4eec\u53ef\u4ee5\u5c06\u5b83\u8f6c\u4e3a\u5b57\u7b26\u4e32\uff0c\u83b7\u53d6\u76f8\u5e94\u7684\u6570\u636e\u3002

\u7b2c\u4e8c\u6b65\u53ef\u4ee5\u5411\u670d\u52a1\u5668\u589e\u52a0\u5546\u54c1\uff0c\u540c\u6837\u7684\u9053\u7406\uff0c\u6211\u4eec\u521b\u5efa\u4e00\u4e2aPOST\u8bf7\u6c42\uff0c\u5e26\u4e0a\u76f8\u5173\u7684\u5546\u54c1\u4fe1\u606f\u5373\u53ef\u3002
//\u521b\u5efa\u4e00\u4e2ahttp\u5ba2\u6237\u7aef
HttpClient client=new DefaultHttpClient();
//\u521b\u5efa\u4e00\u4e2aPOST\u8bf7\u6c42
HttpPost httpPost=new HttpPost("http://www.store.com/product");
//\u7ec4\u88c5\u6570\u636e\u653e\u5230HttpEntity\u4e2d\u53d1\u9001\u5230\u670d\u52a1\u5668
final List dataList = new ArrayList();
dataList.add(new BasicNameValuePair("productName", "cat"));
dataList.add(new BasicNameValuePair("price", "14.87"));
HttpEntity entity = new UrlEncodedFormEntity(dataList, "UTF-8");
httpPost.setEntity(entity);
//\u5411\u670d\u52a1\u5668\u53d1\u9001POST\u8bf7\u6c42\u5e76\u83b7\u53d6\u670d\u52a1\u5668\u8fd4\u56de\u7684\u7ed3\u679c\uff0c\u53ef\u80fd\u662f\u589e\u52a0\u6210\u529f\u8fd4\u56de\u5546\u54c1ID\uff0c\u6216\u8005\u5931\u8d25\u7b49\u4fe1\u606f
HttpResponse response=client.execute(httpPost);
\u7b2c\u4e09\u6b65\u662f\u5982\u679c\u4fee\u6539\u5546\u54c1\u4fe1\u606f\uff0c\u6211\u4eec\u53ea\u9700\u8981\u521b\u5efa\u4e00\u4e2aPUT\u8bf7\u6c42\uff0c\u5e26\u4e0a\u8981\u4fee\u6539\u7684\u53c2\u6570\u5373\u53ef\u3002\u672c\u4f8b\u5047\u8bbe\u7b2c\u4e09\u6b65\u4e2d\u589e\u52a0\u7684\u5546\u54c1\u8fd4\u56deID\u4e3a1234\uff0c\u4e0b\u9762\u5c06\u4e3a\u5546\u54c1\u7684\u4ef7\u683c\u4fee\u6539\u4e3a11.99.

//\u521b\u5efa\u4e00\u4e2ahttp\u5ba2\u6237\u7aef
HttpClient client=new DefaultHttpClient();
//\u521b\u5efa\u4e00\u4e2aPUT\u8bf7\u6c42
HttpPut httpPut=new HttpPut("http://www.store.com/product/1234");
//\u7ec4\u88c5\u6570\u636e\u653e\u5230HttpEntity\u4e2d\u53d1\u9001\u5230\u670d\u52a1\u5668
final List dataList = new ArrayList();
dataList.add(new BasicNameValuePair("price", "11.99"));
HttpEntity entity = new UrlEncodedFormEntity(dataList, "UTF-8");
httpPut.setEntity(entity);
//\u5411\u670d\u52a1\u5668\u53d1\u9001PUT\u8bf7\u6c42\u5e76\u83b7\u53d6\u670d\u52a1\u5668\u8fd4\u56de\u7684\u7ed3\u679c\uff0c\u53ef\u80fd\u662f\u4fee\u6539\u6210\u529f\uff0c\u6216\u8005\u5931\u8d25\u7b49\u4fe1\u606f
HttpResponse response=client.execute(httpPut);
\u7b2c\u56db\u6b65\u6211\u4eec\u628a\u4e0a\u9762\u589e\u52a0\u7684\u5546\u54c1\u5220\u9664\uff0c\u53ea\u9700\u8981\u5411\u670d\u52a1\u5668\u53d1\u9001\u4e00\u4e2aDELETE\u8bf7\u6c42\u5373\u53ef\u3002

//\u521b\u5efa\u4e00\u4e2ahttp\u5ba2\u6237\u7aef
HttpClient client=new DefaultHttpClient();
//\u521b\u5efa\u4e00\u4e2aDELETE\u8bf7\u6c42
HttpDelete httpDelete=new HttpDelete("http://www.store.com/product/1234");
//\u5411\u670d\u52a1\u5668\u53d1\u9001DELETE\u8bf7\u6c42\u5e76\u83b7\u53d6\u670d\u52a1\u5668\u8fd4\u56de\u7684\u7ed3\u679c\uff0c\u53ef\u80fd\u662f\u5220\u9664\u6210\u529f\uff0c\u6216\u8005\u5931\u8d25\u7b49\u4fe1\u606f
HttpResponse response=client.execute(httpDelete);
\u597d\u4e86\uff0c\u5c31\u8fd9\u4e48\u7b80\u5355\uff0c\u8fd9\u6837\u5c31\u5b9e\u73b0\u4e86\u4eceandroid\u5ba2\u6237\u7aef\u8c03\u7528Rest\u670d\u52a1\u5bf9\u8d44\u6e90\u8fdb\u884c\u589e\u3001\u5220\u3001\u6539\u3001\u67e5\u64cd\u4f5c\u3002

\u5e0c\u671b\u672c\u6587\u5bf9\u60a8\u6709\u6240\u5e2e\u52a9\uff01

spring 集成测试中 对mock 的集成实在是太棒了!但是使用请注意一下3个条件。

junit 必须使用4.9以上

同时您的框架必须是用spring mvc

spring 3.2以上才完美支持

目前使用spring MVC 取代struts2 的很多,spring MVC 的各种灵活让人无比销魂!所以使用spring MVC吧!

以前在对接口(主要是java服务端提供的接口(一般是:webService,restful))进行测试的中 一般用以下俩种方法。测试流程如图:

1 直接使用httpClient

   这方法各种麻烦

2 使用Spring 提供的RestTemplate

   错误不好跟踪,必须开着服务器

使用mockMVC都不是问题了看使用实例:

使用事例如下:父类

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]}")  

                   );  

   }  

上面是简单的例子,实际使用起来可以稍做修改。记得导入spring -test jar 包。无需额外配置(是不是很方便!)

当然和junit 的assert 一起用的话效果更好。下面贴点例子。copy就能跑。

Java代码  

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;  

         

   }  

     

}  

使用如下:

Java代码  

@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执行时都会执行一次的,所以有些需要每次都实例化的参数可以放进来

如下:

Java代码  

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

   }  

ok!基本使用大致如此,代码没有些注释,但是很简单,看懂是没问题的。权当抛砖引玉。希望大家加以指正!



扩展阅读:spring mvc流程面试 ... spring mvc运行流程 ... springmvc处理流程图 ... springcloud面试题及答案 ... 简述spring mvc流程 ... springmvc面试题及答案 ... spring mvc怎么使用 ... spring mvc工作流程图解 ... spring mvc要学多久 ...

本站交流只代表网友个人观点,与本站立场无关
欢迎反馈与建议,请联系电邮
2024© 车视网