出于某种原因,如果我通过浏览器或通过我的 MockMVC 测试类访问 Spring Controller ,它会返回不同的响应。 有人能帮我找出原因吗?
首先是 Controller 方法:
@RequestMapping(value = APPLICATIONS_ROOT, method = GET)
public HttpEntity<ApplicationsListResource> listApplications(@PageableDefault(page = DEFAULT_START,
size = DEFAULT_HITS_PER_PAGE) Pageable pageable) {
Page<Application> applications = applicationRepository.findAll(pageable);
ApplicationsListResource applicationListResource = new ApplicationsListResource(applications, pageable);
return new ResponseEntity<ApplicationsListResource>(applicationListResource, HttpStatus.OK);
}
显然其中有一些未知的类。 ApplicationListResource
扩展了 ResourceSupport
并包含名为 applications
的 ApplicationResource
列表。此 ApplicationResource
还扩展了 ResourceSupport
。
当我通过浏览器访问代码时,我会得到如下内容:
{
"_links": {
"self": {
"href": "http://localhost:10000/applications{?page,size,sort}",
"templated": true
}
},
"_embedded": {
"applications": [{
"displayname": "One",
"description": "My Test Application!",
"locations": ["http://foo.com"],
"_links": {
"self": { "href": "http://localhost:10000/applications/one" }
}
}, {
...
}]
},
"page": {
"size": 20,
"totalElements": 7,
"totalPages": 1,
"number": 0
}
}
在我看来,HATEOAS 很合规。但是当我通过 MockMVC 请求时...
getMockMvc().perform(get(APPLICATIONS_ROOT)).andExpect(status().isOk()).andExpect(content().contentType(MediaTypes.HAL_JSON)).andExpect(jsonPath("$._embedded.applcations", hasSize(5))).andReturn();
响应中没有符合 HATEOAS 的元素,因此我的测试在 jsonPath 检查中失败:
{
"page" : 0,
"size" : 10,
"sort" : null,
"total" : 5,
"applications" : [ {
"name" : "one",
"version" : "1.0",
...
我尝试更改 MockMVC 方法的 GET 请求上的 ContentType,但没有什么区别。在浏览器中,我没有设置任何特定的内容类型、标题等。
我知道 MockMVC 类使其 HTTP 请求与通常的 RestTemplate 有一定的差异,所以也许是这样的?有人能看到我遗漏的任何明显的东西吗?
如果需要,我会添加额外的代码,但这会使问题比现在更加冗长。
最佳答案
Spring HATEOAS 添加了用于正确渲染 hal 的附加配置,请检查此以了解详细信息:http://docs.spring.io/spring-hateoas/docs/0.19.0.RELEASE/reference/html/#configuration .
简而言之,它将 Jackson2HalModule
和 HalHandlerInstantiator
添加的适当的 MixIn
添加到 ObjectMapper
中。全部在 HypermediaSupportBeanDefinitionRegistrar.java
( https://github.com/spring-projects/spring-hateoas/blob/master/src/main/java/org/springframework/hateoas/config/HypermediaSupportBeanDefinitionRegistrar.java )
如果您使用独立的mockMvc配置,则必须手动配置ObjectMapper
以模仿spring的行为。我遇到了同样的问题,最终在我的测试中添加了以下配置:
mockMvc = MockMvcBuilders.standaloneSetup(controller)
.setMessageConverters(
new MappingJackson2HttpMessageConverter(configureObjectMapper()))
.build();
和
private ObjectMapper configureObjectMapper() {
return Jackson2ObjectMapperBuilder.json()
.modules(new Jackson2HalModule())
.handlerInstantiator(new Jackson2HalModule.HalHandlerInstantiator(
new DelegatingRelProvider(
OrderAwarePluginRegistry.create(Arrays.asList(
new EvoInflectorRelProvider(),
new AnnotationRelProvider()))),
null))
.build();
}
关于java - Spring 的 MockMVC 响应与浏览器响应不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33127031/