Skip to main content
 首页 » 编程设计

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

2024年05月10日11cmt

我正在尝试测试一种使用 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