DataSetDownloadController { @GetMapping(value = "/dataset/export") @ResponseBody public ResponseEntity<Resource> exportDataSet() throws IOException { String dataSet = demoService.exportDataSet(); byte[] dataSetBytes = dataSet.getBytes(StandardCharsets.UTF_8); try (InputStream is = new ByteArrayInputStream(dataSetBytes)) { HttpHeaders headers = new HttpHeaders(); ContentDisposition attachment = ContentDisposition.builder("attachment") .filename("vrp_data_set.yaml") .build(); headers.setContentDisposition(attachment); return ResponseEntity.ok() .headers(headers) .contentLength(dataSetBytes.length) .contentType(new MediaType("text", "x-yaml", StandardCharsets.UTF_8)) .body(new InputStreamResource(is)); } } DataSetDownloadController(DemoService demoService); @GetMapping(value = "/dataset/export") @ResponseBody ResponseEntity<Resource> exportDataSet();  }
@Test void export() throws IOException { String msg = "dummy string"; when(demoService.exportDataSet()).thenReturn(msg); ResponseEntity<Resource> responseEntity = controller.exportDataSet(); assertThat(responseEntity.getStatusCode()).isEqualTo(HttpStatus.OK); HttpHeaders headers = responseEntity.getHeaders(); assertThat(headers.getContentLength()).isEqualTo(msg.length()); assertThat(headers.getContentType()).isNotNull(); assertThat(headers.getContentType().toString()).isEqualToIgnoringWhitespace("text/x-yaml;charset=UTF-8"); assertThat(headers.getContentDisposition()).isNotNull(); String contentDisposition = headers.getContentDisposition().toString(); assertThat(contentDisposition) .startsWith("attachment;") .containsPattern("; *filename=\".*\\.yaml\""); }
@Test void content_length_should_be_number_of_bytes() throws IOException { String msg = "অ"; when(demoService.exportDataSet()).thenReturn(msg); ResponseEntity<Resource> responseEntity = controller.exportDataSet(); assertThat(responseEntity.getHeaders().getContentLength()).isEqualTo(3); }