问题
I'm new inWireMock
. I am running the WireMock
server as a standalone process. I am able to mock simple rest api, by configuring json files under /mappings
folder. Now, I want to mock a file downloading end point. How can I do that?
I don't know if it helps, the end point is in Java/Spring, which looks like this:
@RequestMapping(value = "xxx/get", method = {RequestMethod.GET})
public ResponseEntity<Object> getFile(HttpServletResponse response) throws Exception {
final Resource fileResource = fileResourceFactoryBean.getObject();
if (fileResource.exists()) {
try (InputStream inputStream = fileResource.getInputStream()) {
IOUtils.copy(inputStream, response.getOutputStream());
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=" + fileResource.getFilename());
response.flushBuffer();
inputStream.close();
return new ResponseEntity<>(HttpStatus.OK);
} catch (Exception e) {
LOGGER.error("Error reading file: ", e);
return new ResponseEntity<Object>("Error reading file.", HttpStatus.BAD_REQUEST);
}
}
return new ResponseEntity<Object>(fileResource.getFilename() + " not found.", HttpStatus.BAD_REQUEST);
}
My response section in the mappings json file looks like this:
"response": {
"status": 200,
"bodyFileName": "fileName", // file under __files directory
"headers": {
"Content-Type": "application/octet-stream"
}
}
回答1:
File downloads are really no different than sending markup or JSON. Web browsers treat a file as a download if they don't recognise the MIME type as one it can render.
To make this happen with WireMock, try:
- Setting the Content-Type header on the response to application/octet-stream
- Setting the response to use a body file (the one you wish to download)
回答2:
A very late answer, but the only working solution I found is this:
"response": {
"status": 200,
"headers": {
"Content-Type": "image/jpeg"
},
"base64Body": "2wBDAAQDAwQDAwQE...=="
}
Where I put the image content, encoded in Base64, directly in the mapping file.
More or less ok...for small files.
In java, it seems a bit more handy :
.willReturn( aResponse()
.withBody( myImage.getBytes() )
Using the json DSL, you only have:
bodyFileName
(NB: the doc says: "body files are expected to be in UTF-8 format")base64Body
- but something like
base64BodyFileName
is NOT possible :-(
来源:https://stackoverflow.com/questions/44119671/wiremock-how-to-mock-file-download-process