java - Spring 的 MockMVC 响应与浏览器响应不匹配

标签 java spring spring-mvc spring-hateoas

出于某种原因,如果我通过浏览器或通过我的 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 并包含名为 applicationsApplicationResource 列表。此 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 .

简而言之,它将 Jackson2HalModuleHalHandlerInstantiator 添加的适当的 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/

相关文章:

java.lang.IllegalStateException : File has already been moved - cannot be transferred again 错误

java - 如何从 fragment 中禁用 Activity 的抽屉导航

java - fatal error - 序言中不允许内容

java - 如何使用 ValueAnimator#ofFloat

当枚举与自定义单元工厂一起使用时,JavaFX 无法设置数据

Spring和jackson,如何通过@ResponseBody禁用FAIL_ON_EMPTY_BEANS

java - Spring MVC ModelAttribute 作为接口(interface)

java - 具有该位置 [5] 的参数不存在;

java - SQL Server与spring的连接

java - Spring MVC与Hibernate持久层集成测试