我正在测试一个控制器:
@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 注入到我的上下文中,但它没有被使用。Serilaization 过程中使用了另一个 ObjectMapper。这是我在测试类中使用 @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;
}
}