我想測試一個使用Spring的MockMVC框架將對象發佈到數據庫的方法。我已經構建瞭如下測試:使用Spring MockMVC測試Spring的@RequestBody
@Test
public 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這種方法嗎?
安置自己的'ObjectBean'類和什麼'json'包含在發送請求之前。 –
根據你的評論更新 – Matt
你將不得不發佈實際的課程。使用400,Spring未能將您的請求體轉換爲ObjectBean對象。 –