WireMock: How to mock file download process?

Viewed 9817

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"
    }
  }
2 Answers

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 :-(
Related