小编典典

尝试测试HTTP POST处理时出现HttpMediaTypeNotSupportedException

spring-mvc

我正在尝试POST在spring框架中测试方法,但是我一直都在出错。

我首先尝试了这个测试:

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

并得到以下错误:

org.springframework.http.converter.HttpMessageNotReadableException

然后我尝试修改测试,如下所示:

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

但是出现了以下错误:
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);
    }
}

其中Testclass有两个字段成员:idwidth。简而言之,我无法为控制器设置参数。

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


阅读 1809

收藏
2020-06-01

共1个答案

小编典典

您应该将内容类型添加MediaType.APPLICATION_JSON到发布请求中,例如

this.mockMvc.perform(post("/rest/tests/")
                .contentType(MediaType.APPLICATION_JSON)
                .content("{\"id\":10,\"width\":1000}"))
                .andDo(MockMvcResultHandlers.print())
                .andExpect(status().isOk());
2020-06-01