• 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 static org.junit.Assert.assertNotNull;
8 
9 import java.io.ByteArrayInputStream;
10 import java.io.ByteArrayOutputStream;
11 import java.io.IOException;
12 import java.io.InputStream;
13 import java.io.ObjectInputStream;
14 import java.io.ObjectOutputStream;
15 
16 public abstract class SimpleSerializationUtil {
17 
18     // TODO use widely
19     @SuppressWarnings("unchecked")
serializeAndBack(T obj)20     public static <T> T serializeAndBack(T obj) throws Exception {
21         ByteArrayOutputStream os = serializeMock(obj);
22         return (T) deserializeMock(os, Object.class);
23     }
24 
deserializeMock(ByteArrayOutputStream serialized, Class<T> type)25     public static <T> T deserializeMock(ByteArrayOutputStream serialized, Class<T> type)
26             throws IOException, ClassNotFoundException {
27         InputStream unserialize = new ByteArrayInputStream(serialized.toByteArray());
28         return deserializeMock(unserialize, type);
29     }
30 
deserializeMock(InputStream unserialize, Class<T> type)31     public static <T> T deserializeMock(InputStream unserialize, Class<T> type)
32             throws IOException, ClassNotFoundException {
33         Object readObject = new ObjectInputStream(unserialize).readObject();
34         assertNotNull(readObject);
35         return type.cast(readObject);
36     }
37 
serializeMock(Object mock)38     public static ByteArrayOutputStream serializeMock(Object mock) throws IOException {
39         ByteArrayOutputStream serialized = new ByteArrayOutputStream();
40         new ObjectOutputStream(serialized).writeObject(mock);
41         return serialized;
42     }
43 }
44