在我的生产代码中,我需要对响应StreamingResponseBody的控制器执行POST命令。此类代码的简短示例是:
@RestController
@RequestMapping("/api")
public class DalaLakeRealController {
@PostMapping(value = "/downloaddbcsv", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<StreamingResponseBody> downloadDBcsv(@Valid @RequestBody SearchQuery searchRequest) {
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_TYPE, "application/csv")
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=demoStream.csv")
.body(
get3Lines()
);
}
public StreamingResponseBody get3Lines() {
StreamingResponseBody streamingResponseBody = new StreamingResponseBody() {
@Override
public void writeTo(OutputStream outputStream) throws IOException {
outputStream.write("LineNumber111111111\n".getBytes());
outputStream.write("LineNumber222222222\n".getBytes());
outputStream.write("LineNumber333333333\n".getBytes());
}
};
return streamingResponseBody;
}
}
在测试中,我想模拟来自此控制器的响应。我已阅读以下链接:Using MockRestServiceServer to Test a REST Client模拟外部控制器。 但是在mockServer的andRespond中,它期望ClientHttpResponse或ResponseCreator
mockServer.expect(once(), requestTo("http://localhost:8080/api/downloaddbcsv"))
.andRespond(withSuccess("{message : 'under construction'}", MediaType.APPLICATION_JSON));
我如何在MockRestServiceServer中使用StreamingResponseBody进行响应?
我希望这会指导您...
@Test
public void whenTopicNotExistsThenTopicNotFound() throws IOException, NakadiException {
when(eventTypeRepository.findByName(TEST_EVENT_TYPE_NAME)).thenThrow(NoSuchEventTypeException.class);
final StreamingResponseBody responseBody = createStreamingResponseBody();
final Problem expectedProblem = Problem.valueOf(NOT_FOUND, "topic not found");
assertThat(responseToString(responseBody), TestUtils.JSON_TEST_HELPER.matchesObject(expectedProblem));
}
想法是将StreamingResponseBody
转换为String
。然后,您可以执行以下操作:
mockServer.expect(once(), requestTo("http://localhost:8080/api/downloaddbcsv"))
.andRespond(withSuccess(responseToString(responseBody), MediaType.APPLICATION_JSON));
streamingResponseBody()
和responseEntity()
测试方法将响应转换为a String
。