1 4 package com.tc.util; 5 6 import com.tc.logging.TCLogger; 7 import com.tc.logging.TCLogging; 8 9 import java.io.ByteArrayInputStream ; 10 import java.io.ByteArrayOutputStream ; 11 import java.io.ObjectInputStream ; 12 import java.io.ObjectOutputStream ; 13 14 import junit.framework.Assert; 15 16 19 public class SerializationTestUtil { 20 21 private static final TCLogger logger = TCLogging.getLogger(SerializationTestUtil.class); 22 23 public static void testSerialization(Object o) throws Exception { 24 testSerialization(o, false, false); 25 } 26 27 public static void testSerializationWithRestore(Object o) throws Exception { 28 testSerialization(o, true, false); 29 } 30 31 public static void testSerializationAndEquals(Object o) throws Exception { 32 testSerialization(o, true, true); 33 } 34 35 public static void testSerialization(Object o, boolean checkRestore, boolean checkEquals) throws Exception { 36 Assert.assertNotNull(o); 37 38 ByteArrayOutputStream baos = new ByteArrayOutputStream (); 39 ObjectOutputStream oos = new ObjectOutputStream (baos); 40 41 oos.writeObject(o); 42 oos.flush(); 43 44 logger.debug("Object " + o + " of class " + o.getClass() + " serialized to " + baos.toByteArray().length 45 + " bytes."); 46 47 if (checkRestore) { 48 ByteArrayInputStream bais = new ByteArrayInputStream (baos.toByteArray()); 49 ObjectInputStream ois = new ObjectInputStream (bais); 50 51 Object restored = ois.readObject(); 52 53 if (checkEquals) { 54 Assert.assertEquals(o, restored); 55 Assert.assertEquals(restored, o); 56 57 Assert.assertEquals(o.hashCode(), restored.hashCode()); 58 59 Assert.assertNotSame(o, restored); 60 } 61 } 62 } 63 64 } | Popular Tags |