Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Gson instead of Jackson for MockMvc?

I have spent the past day trying to find a solution to this and could not find any online resource that solves this.

I am using Gson for Message conversion for my application, which works fine outside of unit testing. I even added a HttpMessageConverters bean to take precedence over Jackson instead of writing config values to application.yml. This only works when running the application.

Now my question is, how do I use the Gson serialization/deserialization for MockMvc? I have a class with the @SerializedName("field_one") annotation which the value differs from the actual name. The closest I got to finding an answer was the one below which didn't help:

https://stackoverflow.com/a/20510028/3948882

Any ideas how to replace the ObjectMapper or have MockMvc use Gson instead of Jackson?


Edit: To add a little more context:

When I try to send a Model which was converted to Json with Gson, it get's immediately refused (400) because I have @NotNull annotation for each field in the model. When it deserializes in the controller, it sets fields to null. The below example has @Valid, which makes sure the Model checks out.

@RequestMapping(value = "accept", method = RequestMethod.POST)
public Model resp(@Valid @RequestBody Model model){
    return model;
}

On the flip side, when I go to hit an endpoint without @Valid, passing a json that pleases Jackson, and I get the a model back, I cannot check any of the fields:

mockMvc.perform(
    post("/test/accept")
        .contentType(MediaType.APPLICATION_JSON)
        .content(json))
    .andExpect(jsonPath("$.field_one", is("Hello world!")))

Exception:

java.lang.AssertionError: No value at JSON path "$.field_one", exception: No results for path: $['field_one']
like image 575
Brandon Avatar asked Oct 29 '22 00:10

Brandon


1 Answers

You have to set-up the MockMvc correctly:

MockMvc mvc = MockMvcBuilders.standaloneSetup(new YourController())
                             .setControllerAdvice(new SomeExceptionHandler())
                             .setMessageConverters(new GsonHttpMessageConverter()) //<-- THIS
                             .build();
like image 98
Eugene Avatar answered Nov 14 '22 17:11

Eugene