MocMVC giving HttpMessageNotReadableException
An HttpMessageNotReadableException
is
Thrown by HttpMessageConverter implementations when the read method fails.
You also get a 400 Bad Request in your response. This should all tell you that you are not sending what your server is expecting. What is your server expecting?
@RequestMapping(value = "/requestpayment", method = RequestMethod.POST, headers="Accept=application/json")
@ResponseBody
public ResponseEntity<PaymentResult> handleRequestPayment(@RequestBody PaymentRequest paymentRequest, HttpServletRequest request, HttpServletResponse response, BindingResult result) throws Exception{
The main thing here is the @RequestBody
annotated parameter. So you are telling your server to try and deserialize a PaymentRequest
instance from the body of the HTTP POST request.
So let's see the request you are making
mockMvc.perform(post("/requestpayment")
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andDo(print())
.andExpect(status().isBadRequest());
I don't see you providing a body to the request. There should be a content(String)
call somewhere in there to set the content of the POST request. This content should be a JSON serialization of a PaymentRequest
.
Note that because you are using the StandaloneMockMvcBuilder
, you might need to set the HttpMessageConverter
instances yourself, ie. a MappingJackson2HttpMessageConverter
to serialize and deserialize JSON.
Note that the BindingResult
parameter should come immediately after the parameter to which it's related. Like so
@RequestMapping(value = "/requestpayment", method = RequestMethod.POST, headers="Accept=application/json")
@ResponseBody
public ResponseEntity<PaymentResult> handleRequestPayment(@Valid @RequestBody PaymentRequest paymentRequest, BindingResult result, HttpServletRequest request, HttpServletResponse response) throws Exception{
Don't forget the @Valid
.
Note that this
requestPaymentController.setLoginService(mockLoginService);
requestPaymentController.handleRequestPayment(mockPaymentRequest, mockHttpServletRequest, mockHttpServletResponse, mockBindingResult);
is completely unrelated to the MockMvc
test you are doing.