PUBLIC OBJECT

Embed binary data in your tests with Okio

Here's some code that uses Okio to serialize an object to a base64-encoded string:

String toBase64(Object object) throws Exception {
  Buffer buffer = new Buffer();
  ObjectOutputStream out = new ObjectOutputStream(buffer.outputStream());
  out.writeObject(object);
  out.close();
  return buffer.readByteString().base64();
}

And this code will deserialize that string back into an object:

<T> T fromBase64(String base64) throws Exception {
  Buffer buffer = new Buffer();
  buffer.write(ByteString.decodeBase64(base64));
  ObjectInputStream in = new ObjectInputStream(buffer.inputStream());
  Object result = in.readObject();
  in.close();
  return (T) result;
}

With these two methods you can take a serialization snapshot of an object running under one version of your code and confirm that it'll deserialize under another.

For example, you can System.out a BloomFilter created with Guava v16:

@Test public void printSerializedObject() throws Exception {
  BloomFilter<Integer> bloomFilter = ...;
  bloomFilter.put(5);
  System.out.println(toBase64(bloomFilter));
}

Copy and paste the printed base64 into another test and confirm that it deserializes correctly under Guava v17:

@Test public void deserialize() throws Exception {
  String goldenValue = "rO0ABXNyAC1jb20uZ29vZ2xlLmNvbW1vbi5oYXNoLkJsb29tRmlsd"
      + "GVyJFNlcmlhbEZvcm0AAAAAAAAAAQIABEkAEG51bUhhc2hGdW5jdGlvbnNbAARkYXRhd"
      + "AACW0pMAAZmdW5uZWx0AB9MY29tL2dvb2dsZS9jb21tb24vaGFzaC9GdW5uZWw7TAAIc"
      + "3RyYXRlZ3l0AC1MY29tL2dvb2dsZS9jb21tb24vaGFzaC9CbG9vbUZpbHRlciRTdHJhd"
      + "GVneTt4cAAAAAV1cgACW0p4IAS1ErF1kwIAAHhwAAAAAYAAAAAAAAkkfnIAIm9raW8uQ"
      + "mxvb21GaWx0ZXJUZXN0JEludGVnZXJGdW5uZWwAAAAAAAAAABIAAHhyAA5qYXZhLmxhb"
      + "mcuRW51bQAAAAAAAAAAEgAAeHB0AAhJTlNUQU5DRX5yACxjb20uZ29vZ2xlLmNvbW1vb"
      + "i5oYXNoLkJsb29tRmlsdGVyU3RyYXRlZ2llcwAAAAAAAAAAEgAAeHEAfgAIdAARTVVST"
      + "VVSMTI4X01JVFpfNjQ=";
  BloomFilter<Integer> bloomFilter = fromBase64(goldenValue);
  assertTrue(bloomFilter.mightContain(5));
}

With base64 it's easy to embed binary data right in the test.

This example exercises serialization, but the technique is handy elsewhere. On a recent project I included encrypted data and the key that decrypts it in a test. The test later detected a regression triggered by updating one of our crypto dependencies!

Find Okio on GitHub.