为Spring控制器测试配置自定义Json Serializer

时间:2017-05-24 16:45:14

标签: spring spring-mvc spring-boot spring-boot-test

我正在测试一个控制器:

@RestController()
public class MessagesController {
...
}

使用@WebMvcTest注释:

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

但是当我启动测试时,Spring会尝试序列化List>类型的对象。它失败了:

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

当我在调试模式下执行时,我发现异常是从以下引发的:com.fasterxml.jackson.databind.ser.std.CollectionSerializer#serializeContents 这是一个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"]).

我还尝试将ObjectMapper注入到我的上下文中,但它没有被使用。另一个ObjectMapper用于Serilaization过程。这是我在我的测试类中使用@Import(HateoasConfiguration.class)注入的ObjectMapper:

@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;
    }

}

0 个答案:

没有答案