1 54 55 package junitx.extensions; 56 57 import junit.framework.AssertionFailedError; 58 import junit.framework.TestCase; 59 60 import java.io.ByteArrayInputStream ; 61 import java.io.ByteArrayOutputStream ; 62 import java.io.ObjectInputStream ; 63 import java.io.ObjectOutputStream ; 64 import java.io.Serializable ; 65 66 76 public abstract class SerializabilityTestCase 77 extends TestCase { 78 79 private Serializable obj; 80 81 86 public SerializabilityTestCase(String name) { 87 super(name); 88 } 89 90 96 protected abstract Serializable createInstance() throws Exception ; 97 98 103 protected void setUp() 104 throws Exception { 105 super.setUp(); 106 107 obj = createInstance(); 108 109 try { 111 assertNotNull("createInstance() returned null", obj); 112 } catch (AssertionFailedError ex) { 113 throw new IllegalArgumentException (ex.getMessage()); 114 } 115 } 116 117 121 public final void testSerializability() 122 throws Exception { 123 ByteArrayOutputStream baos = new ByteArrayOutputStream (); 124 ObjectOutputStream oos = new ObjectOutputStream (baos); 125 oos.writeObject(obj); 126 oos.flush(); 127 oos.close(); 128 129 byte[] frozenChunk = baos.toByteArray(); 130 baos.close(); 131 132 ByteArrayInputStream bais = new ByteArrayInputStream (frozenChunk); 133 ObjectInputStream ois = new ObjectInputStream (bais); 134 Serializable thawed = (Serializable ) ois.readObject(); 135 136 checkThawedObject(obj, thawed); 137 } 138 139 149 protected void checkThawedObject(Serializable expected, 150 Serializable actual) 151 throws Exception { 152 assertEquals("thawed object comparison", expected, actual); 153 } 154 155 } 156 | Popular Tags |