• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2017 Mockito contributors
3  * This program is made available under the terms of the MIT License.
4  */
5 package org.mockitoutil;
6 
7 import java.io.*;
8 
9 import static org.junit.Assert.assertNotNull;
10 
11 public abstract class SimpleSerializationUtil {
12 
13     //TODO use widely
14     @SuppressWarnings("unchecked")
serializeAndBack(T obj)15     public static <T> T serializeAndBack(T obj) throws Exception {
16         ByteArrayOutputStream os = serializeMock(obj);
17         return (T) deserializeMock(os, Object.class);
18     }
19 
deserializeMock(ByteArrayOutputStream serialized, Class<T> type)20     public static <T> T deserializeMock(ByteArrayOutputStream serialized, Class<T> type) throws IOException,
21             ClassNotFoundException {
22         InputStream unserialize = new ByteArrayInputStream(serialized.toByteArray());
23         return deserializeMock(unserialize, type);
24     }
25 
deserializeMock(InputStream unserialize, Class<T> type)26     public static <T> T deserializeMock(InputStream unserialize, Class<T> type) throws IOException, ClassNotFoundException {
27         Object readObject = new ObjectInputStream(unserialize).readObject();
28         assertNotNull(readObject);
29         return type.cast(readObject);
30     }
31 
serializeMock(Object mock)32     public static ByteArrayOutputStream serializeMock(Object mock) throws IOException {
33         ByteArrayOutputStream serialized = new ByteArrayOutputStream();
34         new ObjectOutputStream(serialized).writeObject(mock);
35         return serialized;
36     }
37 }
38