gpt4 book ai didi

spring-mvc - 使用 Spring MockMVC 测试 Spring 的 @RequestBody

转载 作者:行者123 更新时间:2023-12-03 06:07:39 29 4
gpt4 key购买 nike

我正在尝试测试一种使用 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 测试这个方法?

最佳答案

使用这个

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)。

More info on the HTTP request body structure

关于spring-mvc - 使用 Spring MockMVC 测试 Spring 的 @RequestBody,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20504399/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com