使用Spring MockMVC测试Spring的@RequestBody [英] Testing Spring's @RequestBody using Spring MockMVC

查看:383
本文介绍了使用Spring MockMVC测试Spring的@RequestBody的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试测试一种使用Spring的MockMVC框架将对象发布到数据库的方法.我将测试构建如下:

I am trying to test a method that posts an object to the database using Spring's MockMVC framework. I've constructed the test as follows:

@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错误.

The method I'm testing uses Spring's @RequestBody to receive the ObjectBean, but the test always returns a 400 error.

@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:

The json created by gson in the test:

{
   "objectId":"33",
   "userId":"4268321",
   //... many more
}

ObjectBean类

The ObjectBean class

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测试此方法?

So my question is: how to I test this method using 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).

As described in the comments, this works because the object is converted to json and passed as the request body. Additionally, the contentType is defined as Json (APPLICATION_JSON_UTF8).

有关HTTP请求正文结构的更多信息

这篇关于使用Spring MockMVC测试Spring的@RequestBody的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆