HttpMediaTypeNotSupportedException while trying to check HTTP POST processing

I am trying to test the POST method as part of spring, but I am constantly getting errors.

First I 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 shown below:

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

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

My controller:

 @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 the Test class has two field members: id and width . In a few words, I can’t set the parameters for the controller.

What is the correct way to set parameters?

+2
source share
1 answer

You must add the content type MediaType.APPLICATION_JSON to the MediaType.APPLICATION_JSON request, for example.

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

Source: https://habr.com/ru/post/1236073/


All Articles