I recently worked on an issue where a json payload with binary content was posted to a rest service which resulted in Blob.toString() raising a 'BLOB is not a valid UTF-8 string' exception. We're base64 encoding these failed payloads and journalling them for future recovery. We were able to recover the failed payloads and the offending client has been fixed.

My question is: I'd like to write a unit test or even a e2e test to verify my solution but I've have not been able to figure out how to generate a similar corrupted json payload. Basically JSON.serialize balks at my attempts to inject binary into my json. Any ideas appreciated.

1 Answer 1


Encode your data in either base-64 or hex, then use the relevant method (EncodingUtil.base64decode or EncodingUtil.convertFromHex) to get the Blob you'd pass in to your resource during the unit test. Or, alternatively, upload the file as a Static Resource, which you can then query and use the body directly from that result. You'll probably want to use an external tool to help you with the conversion, such as uuencode available on most modern Linux systems (also available in Windows if you search for it).

Not the answer you're looking for? Browse other questions tagged or ask your own question.