使用Spring MockMVC测试Spring的@RequestBody
我正在尝试测试使用Spring的MockMVC框架将对象发布到数据库的方法。我将测试构建如下:
@Testpublic void testInsertObject() throws Exception {
String url = BASE_URL + "/object";
ObjectBean anObject = new ObjectBean();
anObject.setObjectId("33");
anObject.setUserId("4268321");
//... more
Gson gson = new Gson();
String json = gson.toJson(anObject);
MvcResult result = this.mockMvc.perform(
post(url)
.contentType(MediaType.APPLICATION_JSON)
.content(json))
.andExpect(status().isOk())
.andReturn();
}
我正在测试的方法使用Spring的@RequestBody接收ObjectBean,但是测试始终返回400错误。
@ResponseBody@RequestMapping( consumes="application/json",
produces="application/json",
method=RequestMethod.POST,
value="/object")
public ObjectResponse insertObject(@RequestBody ObjectBean bean){
this.photonetService.insertObject(bean);
ObjectResponse response = new ObjectResponse();
response.setObject(bean);
return response;
}
gson在测试中创建的json:
{ "objectId":"33",
"userId":"4268321",
//... many more
}
ObjectBean类
public class ObjectBean {private String objectId;
private String userId;
//... many more
public String getObjectId() {
return objectId;
}
public void setObjectId(String objectId) {
this.objectId = objectId;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
//... many more
}
所以我的问题是:如何使用Spring MockMVC测试此方法?
回答:
public static final MediaType APPLICATION_JSON_UTF8 = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8"));@Test
public void testInsertObject() throws Exception {
String url = BASE_URL + "/object";
ObjectBean anObject = new ObjectBean();
anObject.setObjectId("33");
anObject.setUserId("4268321");
//... more
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
ObjectWriter ow = mapper.writer().withDefaultPrettyPrinter();
String requestJson=ow.writeValueAsString(anObject );
mockMvc.perform(post(url).contentType(APPLICATION_JSON_UTF8)
.content(requestJson))
.andExpect(status().isOk());
}
如评论中所述,这是有效的,因为对象被转换为json并作为请求主体传递。此外,contentType被定义为Json(APPLICATION_JSON_UTF8)。
有关HTTP请求主体结构的更多信息
以上是 使用Spring MockMVC测试Spring的@RequestBody 的全部内容, 来源链接: utcz.com/qa/420328.html