Setting up a custom Json Serializer for testing a Spring controller
I am testing a controller:
@RestController()
public class MessagesController {
...
}
Using @WebMvcTest annotation:
@RunWith(SpringRunner.class)
@WebMvcTest(value = {MessagesController.class})
public class MessagesControllerTest {
private MockMvc mvc;
....
this.mvc.perform(
get("/messages/{id}", "dummyId")
.contentType(MediaType.APPLICATION_JSON))
.andDo(print())
.andExpect(status().isOk());
...
But when I run my test, Spring tries to serialize an object of type List> and it fails:
Resolved Exception:
Type = org.springframework.http.converter.HttpMessageNotWritableException
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 500
Error message = null
Headers = {Content-Type=[application/json;charset=UTF-8]}
Content type = application/json;charset=UTF-8
Body =
Forwarded URL = null
Redirected URL = null
Cookies = []
java.lang.AssertionError: Status
Expected :200
Actual :500
When I execute execution in debug mode, I found that an exception was thrown from: com.fasterxml.jackson.databind.ser.std.CollectionSerializer # serializeContents And this is a JsonMappingException:
com.fasterxml.jackson.databind.JsonMappingException: Unwrapped property requires use of type information: can not serialize without disabling `SerializationFeature.FAIL_ON_UNWRAPPED_TYPE_IDENTIFIERS` (through reference chain: org.springframework.hateoas.Resource["content"]).
I also tried to inject ObjectMapper into my context but it was not used. Another ObjectMapper is used in the Serialization process. This is the ObjectMapper that I am embedding using @Import (HateoasConfiguration.class) into my test class:
@EnableHypermediaSupport(type = EnableHypermediaSupport.HypermediaType.HAL)
@Configuration
public class HateoasConfiguration
{
private static final String SPRING_HATEOAS_OBJECT_MAPPER = "_halObjectMapper";
@Autowired
@Qualifier(SPRING_HATEOAS_OBJECT_MAPPER)
private ObjectMapper springHateoasObjectMapper;
@Bean(name = "objectMapper")
public ObjectMapper objectMapper() {
springHateoasObjectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
springHateoasObjectMapper.disable(SerializationFeature.FAIL_ON_UNWRAPPED_TYPE_IDENTIFIERS);
springHateoasObjectMapper.registerModules(
new ParameterNamesModule(),
new Jdk8Module(),
new JavaTimeModule(),
new URNModule()
);
return springHateoasObjectMapper;
}
}
+3
source to share
No one has answered this question yet
Check out similar questions: