Testing Keys and Values for Serializability

In distributed caching, cache keys and cached values routinely travel across the network. That's why it is critical to write proper unit tests for keys and values in order to avoid unpleasant production surprises. This article tells how to test keys and values for distributed caching.

Distributed caching imposes an additional requirement towards unit tests for cache keys and cached values. Particularly, you must ensure that the object that was received at another end is the object that was sent. Here is how to tests it:

First, serialize an object to a byte array and then deserialize the byte array back to an object:

// Serialize the object
      ByteArrayOutputStream baos = new ByteArrayOutputStream(100);
      ObjectOutputStream oos = new ObjectOutputStream(baos);
      oos.writeObject(originalInvoiceKey);
      oos.close();

      // Deserialize the object in serialized form
      final byte[] serializedInvoiceKey = baos.toByteArray();
      ByteArrayInputStream bais = new ByteArrayInputStream(serializedInvoiceKey);
      ObjectInputStream ois = new ObjectInputStream(bais);
      final InvoiceKey deserializedInvoiceKey = (InvoiceKey) ois.readObject();
      ois.close();

Second, assert that the deserialized object and the original object are equal:

assertEquals(originalInvoiceKey, deserializedInvoiceKey);

While you have already implemented methods equals() and hashCode() for the key, cached values need to have that methods added. For value objects, equals() and hashCode() need to satisfy a requirement for 'literal equality'. In other words, to test that a value object can be serialized and deserialized, its equals() and hashCode() should include all non-transient fields:

public final class Invoice implements Externalizable {

   private int invoiceID;
   private Date invoiceDate = null;
   private int invoiceNumber;
   private int customerID;

...

   public boolean equals(final Object o) {
      if (this == o) return true;
      if (o == null || getClass() != o.getClass()) return false;
      final Invoice invoice = (Invoice) o;
      if (invoiceID != invoice.invoiceID) return false;
      if (invoiceNumber != invoice.invoiceNumber) return false;
      if (customerID != invoice.customerID) return false;
      if (invoiceDate != null ? !invoiceDate.equals(invoice.invoiceDate) : invoice.invoiceDate != null) return false;
      return true;
   }

   public int hashCode() {
      int result = invoiceID;
      result = 31 * result + (invoiceDate != null ? invoiceDate.hashCode() : 0);
      result = 31 * result + invoiceNumber;
      result = 31 * result + customerID;
      return result;
   }
}

If adding equals() and hashCode() to the cached value is impossible, use explicit assertEquals() for object's fields:

assertEquals(invoiceID, deserializedInvoiceKey.getInvoiceID());

Here is a complete example of a unit test for distributed cache key and value.

Labels

 
(None)