尝试测试HTTP POST的处理时HttpMediaTypeNotSupportedException

use*_*893 2 spring unit-testing http spring-mvc

我试图POST在spring框架中测试方法,但我一直都在犯错误.

我第一次尝试这个测试:

this.mockMvc.perform(post("/rest/tests").
                            param("id", "10").
                            param("width","25")
                            )
                .andDo(MockMvcResultHandlers.print())
                .andExpect(status().isOk());
Run Code Online (Sandbox Code Playgroud)

并得到以下错误:

org.springframework.http.converter.HttpMessageNotReadableException

然后我尝试修改测试如下:

this.mockMvc.perform(post("/rest/tests/").
                            content("{\"id\":10,\"width\":1000}"))
                .andDo(MockMvcResultHandlers.print())
                .andExpect(status().isOk());              
Run Code Online (Sandbox Code Playgroud)

但得到以下错误:
org.springframework.web.HttpMediaTypeNotSupportedException

我的控制器是:

@Controller
@RequestMapping("/rest/tests")
public class TestController {

    @Autowired
    private ITestService testService;

    @RequestMapping(value="", method=RequestMethod.POST)
    @ResponseStatus(value = HttpStatus.OK)
    public void add(@RequestBody Test test)
    {
        testService.save(test);
    }
}
Run Code Online (Sandbox Code Playgroud)

Test类有两个字段成员:idwidth.简而言之,我无法为控制器设置参数.

设置参数的正确方法是什么?

Mas*_*ave 5

您应该MediaType.APPLICATION_JSON为帖子请求添加内容类型,例如

this.mockMvc.perform(post("/rest/tests/")
                .contentType(MediaType.APPLICATION_JSON)
                .content("{\"id\":10,\"width\":1000}"))
                .andDo(MockMvcResultHandlers.print())
                .andExpect(status().isOk()); 
Run Code Online (Sandbox Code Playgroud)