HttpMediaTypeNotSupportedException when trying to test handling of HTTP POST

余生颓废 提交于 2020-01-04 15:15:05

问题


I am trying to test POST method in spring framework but I keep getting errors all the time.

I first tried this test:

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

and got the following error:

org.springframework.http.converter.HttpMessageNotReadableException

Then I tried to modify the test as below:

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

But got the following error:
org.springframework.web.HttpMediaTypeNotSupportedException

My controller is:

@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);
    }
}

Where Test class has two field members: id and width. In a few word I am unable to set the parameters for the controller.

What's the proper way to set the parameters?


回答1:


You should add a content type MediaType.APPLICATION_JSON to the post request, e.g.

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


来源:https://stackoverflow.com/questions/31609496/httpmediatypenotsupportedexception-when-trying-to-test-handling-of-http-post

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!