user3764893
user3764893

Reputation: 707

HttpMediaTypeNotSupportedException when trying to test handling of HTTP POST

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?

Upvotes: 2

Views: 1689

Answers (1)

Master Slave
Master Slave

Reputation: 28519

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()); 

Upvotes: 6

Related Questions