我的示例应用程序中有一个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);
}
单元测试
@Test
public void testGetHomePageCollection() {
when(collectionService.getHomePageCollections()).thenReturn(null);
ResponseEntity responseEntity = collectionController.getHomePageCollections(HEADER_APP_TOKEN);
assertThat(responseEntity.getStatusCode()).isEqualTo(HttpStatus.NO_CONTENT);
}
答案 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);
}