Home | History | Annotate | Download | only in mockitoutil
      1 package org.mockitoutil;
      2 
      3 import java.io.*;
      4 
      5 import static junit.framework.TestCase.assertNotNull;
      6 
      7 public abstract class SimpleSerializationUtil {
      8 
      9     //TODO use widely
     10     @SuppressWarnings("unchecked")
     11     public static <T> T serializeAndBack(T obj) throws Exception {
     12         ByteArrayOutputStream os = serializeMock(obj);
     13         return (T) deserializeMock(os, Object.class);
     14     }
     15 
     16     public static <T> T deserializeMock(ByteArrayOutputStream serialized, Class<T> type) throws IOException,
     17             ClassNotFoundException {
     18         InputStream unserialize = new ByteArrayInputStream(serialized.toByteArray());
     19         return deserializeMock(unserialize, type);
     20     }
     21 
     22     public static <T> T deserializeMock(InputStream unserialize, Class<T> type) throws IOException, ClassNotFoundException {
     23         Object readObject = new ObjectInputStream(unserialize).readObject();
     24         assertNotNull(readObject);
     25         return type.cast(readObject);
     26     }
     27 
     28     public static ByteArrayOutputStream serializeMock(Object mock) throws IOException {
     29         ByteArrayOutputStream serialized = new ByteArrayOutputStream();
     30         new ObjectOutputStream(serialized).writeObject(mock);
     31         return serialized;
     32     }
     33 }
     34