【发布时间】:2013-12-28 13:20:43
【问题描述】:
我正在尝试使用 Spring 的 MockMVC 框架测试将对象发布到数据库的方法。我构建了如下测试:
@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 测试此方法?
【问题讨论】:
-
您必须发布实际课程。使用 400,Spring 无法将您的请求正文转换为
ObjectBean对象。 -
感谢 Sotirios,这是我正在调查的日期格式问题。我正在传递一个 java.util 日期,而 gson 不喜欢它。
-
嗨,Sotirios。是的,不幸的是,这个问题仍然存在!我在这里问了一个关于日期格式的问题:stackoverflow.com/questions/20509883/mysql-insert-gson-date
-
ObjectBean类中日期字段的类型是什么?java.util.Date、java.util.Calendar还是String?还是其他?
标签: spring-mvc integration-testing