Mocks with Binary Downloads
To mock a binary response or download, add an attachment to a response with an empty body.
Services Can Return Binary Files
While most services exchange JSON or XML, sometimes they need to send a binary file to the client. Maybe they need to provide a PDF with the customer invoice, or perhaps they need to generate a unique image based on user info.
In the REST world, however, you can be much more flexible. Want to return the binary file as an attachment? You can do that. Send it as a base64 field in a JSON response? You can do that, too. Provide a link to a file to download? Sure.
There are possibly dozens of other ways you can come up with.
Return as HTTP Returns It
Today, however, I’ll cover another option: returning the binary file the same way as a plain HTTP server does. That is the same way files are downloaded from the Internet.
That response has no JSON payload. And yet one can argue that it is a valid REST response.
Suppose we have a REST service that takes some parameters and generates a small robot image in PNG format.
The response is simply the PNG itself:
HTTP/1.1 200 OK Date: Tue, 12 Feb 2019 02:28:07 GMT Content-Type: image/png Content-Length: 3407 �PNG ...
How can we mock it?
MockMotor and Binary Payloads
MockMotor cannot generate binary payloads. It can add binary attachments to a response. However, an attachment is not a top-level data and instead is placed into a multi-part section.
Single Attachment + Empty Payload = Download
MockMotor, however, has a useful convention.
If the response payload field is totally empty and the attachment field contains exactly one attachment, that attachment is sent to the caller as a binary download.
This convention makes sense:
- If we generate any payload, we clearly want to have a payload and an attachment sent back.
- If we have more than one attachment, it cannot be a download.
- If we do not generate any payload, we want a download sent back.
- Finally, if we want an empty payload and attachment sent back (rare but not an impossible case), we can configure the payload as
""(empty string). The payload script is not empty (it contains a script consisting of a string
""), and so MockMotor sends back an empty payload (the result of executing
"") and an attachment.
Let’s review an example response that produces a download:
Add the Binary File as Attachment
Attachments and click
Upload the desired attachment. Edit its name, if required:
Here we’ve uploaded a PNG image named
Leave Payload Completely Empty
In our response, do not put any content, not a single character, into the payload field:
Although the field begs you to put the response there, don’t do that. Not this time.
Add Attachment to the Response
Finally, add the
Robot1.png attachment to the
You only need to specify the attachment name. The content type is kept in the attachment record.
That’s it! Now you can point your testing tool or code to the service, and you should see the download.