1 5 6 package org.springframework.util; 7 8 import java.awt.Point ; 9 import java.io.ByteArrayInputStream ; 10 import java.io.ByteArrayOutputStream ; 11 import java.io.IOException ; 12 import java.io.NotSerializableException ; 13 import java.io.ObjectInputStream ; 14 import java.io.ObjectOutputStream ; 15 import java.io.OutputStream ; 16 import java.io.Serializable ; 17 18 import junit.framework.TestCase; 19 20 import org.springframework.beans.TestBean; 21 22 29 public class SerializationTestUtils extends TestCase { 30 31 public static void testSerialization(Object o) throws IOException { 32 OutputStream baos = new ByteArrayOutputStream (); 33 ObjectOutputStream oos = new ObjectOutputStream (baos); 34 oos.writeObject(o); 35 } 36 37 public static boolean isSerializable(Object o) throws IOException { 38 try { 39 testSerialization(o); 40 return true; 41 } 42 catch (NotSerializableException ex) { 43 return false; 44 } 45 } 46 47 public static Object serializeAndDeserialize(Object o) throws IOException , ClassNotFoundException { 48 ByteArrayOutputStream baos = new ByteArrayOutputStream (); 49 ObjectOutputStream oos = new ObjectOutputStream (baos); 50 oos.writeObject(o); 51 oos.flush(); 52 baos.flush(); 53 byte[] bytes = baos.toByteArray(); 54 55 ByteArrayInputStream is = new ByteArrayInputStream (bytes); 56 ObjectInputStream ois = new ObjectInputStream (is); 57 Object o2 = ois.readObject(); 58 59 return o2; 60 } 61 62 public SerializationTestUtils(String s) { 63 super(s); 64 } 65 66 public void testWithNonSerializableObject() throws IOException { 67 TestBean o = new TestBean(); 68 assertFalse(o instanceof Serializable ); 69 70 assertFalse(isSerializable(o)); 71 72 try { 73 testSerialization(o); 74 fail(); 75 } 76 catch (NotSerializableException ex) { 77 } 79 } 80 81 public void testWithSerializableObject() throws Exception { 82 int x = 5; 83 int y = 10; 84 Point p = new Point (x, y); 85 assertTrue(p instanceof Serializable ); 86 87 testSerialization(p); 88 89 assertTrue(isSerializable(p)); 90 91 Point p2 = (Point ) serializeAndDeserialize(p); 92 assertNotSame(p, p2); 93 assertEquals(x, (int) p2.getX()); 94 assertEquals(y, (int) p2.getY()); 95 } 96 97 } 98 | Popular Tags |