In my production code I need to execute POST command to a controller which response StreamingResponseBody. A short example of such code is :
@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;
}
}
In the testing I would like to mock the response from this controller. I have read the following link :
Using MockRestServiceServer to Test a REST Client to mock external controllers.
But in andRespond of mockServer it expects ClientHttpResponse or ResponseCreator
mockServer.expect(once(), requestTo("http://localhost:8080/api/downloaddbcsv"))
.andRespond(withSuccess("{message : 'under construction'}", MediaType.APPLICATION_JSON));
How do I respond with StreamingResponseBody in MockRestServiceServer?
I hope this will guide you...
Got the above code from: https://www.programcreek.com/java-api-examples/index.php?api=org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody
The idea is to convert the
StreamingResponseBodyinto aString. Then you can do something like:Furthermore, take a look here: https://github.com/spring-projects/spring-framework/blob/master/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/StreamingResponseBodyReturnValueHandlerTests.java
The
streamingResponseBody()andresponseEntity()test methods convert the response to aString.