如何声明由SpringFramework的org.springframework.http.ResponseEntity类设置的“ Content-Type”?

时间:2019-04-29 05:53:45

标签: java spring spring-boot

我的示例应用程序中有一个GET Rest-endpoint,它根据条件返回一些数据,如果HTTP状态为204时没有可用数据,则返回null,如果数据可用则返回200 OK

@GetMapping("/homepage")
    public ResponseEntity getHomePageCollections(@RequestHeader(value = HEADER_APP_TOKEN) String headerAppToken) {
        CollectionObject homepageCollections = null;
        String errorMessage = null;
        HttpStatus httpStatus;
        try {
            homepageCollections = collectionService.getHomePageCollections();
            if (nonNull(homepageCollections)) {
                httpStatus = HttpStatus.OK;
                LOGGER.info("{} Response Status from CollectionController -- getHomePageCollections !! {}", TRANSACTION_SUCCESS_CODE, TRANSACTION_SUCCESS);
            } else {
                httpStatus = HttpStatus.NO_CONTENT;
                LOGGER.info("{} Response Status from CollectionController -- getHomePageCollections !! {}", NO_CONTENT_CODE, NO_CONTENT);
            }
        } // catch logic
        return ResponseEntity.status(httpStatus).contentType(MediaType.APPLICATION_JSON).body(httpStatus == HttpStatus.OK || httpStatus == HttpStatus.NO_CONTENT ? homepageCollections : errorMessage);
    }
  • 我有2个问题,首先是如何声明内容类型是 由控制器在我的单元测试中设置

单元测试

@Test
    public void testGetHomePageCollection() {
        when(collectionService.getHomePageCollections()).thenReturn(null);

        ResponseEntity responseEntity = collectionController.getHomePageCollections(HEADER_APP_TOKEN);
        assertThat(responseEntity.getStatusCode()).isEqualTo(HttpStatus.NO_CONTENT);
    }
  • homepageCollections 为null时,spring会将内容类型自动设置为 octet-stream ,这背后有原因吗?

1 个答案:

答案 0 :(得分:2)

ContentType出现在响应的标题中,因此您可以通过如下方式对其进行测试:

@Test
        public void testGetHomePageCollection() {
            when(collectionService.getHomePageCollections()).thenReturn(null);

            ResponseEntity responseEntity = collectionController.getHomePageCollections(HEADER_APP_TOKEN);
            assertThat(responseEntity.getStatusCode()).isEqualTo(HttpStatus.NO_CONTENT);
            assertThat(responseEntity.getHeaders().getContentType()).isEqualTo(MediaType.APPLICATION_JSON_VALUE);
        }