vendredi 24 juillet 2015

Test post method in spring

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?

Aucun commentaire:

Enregistrer un commentaire