1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32 package com.cedarsoft.serialization;
33
34 import org.apache.commons.io.IOUtils;
35 import org.junit.experimental.theories.*;
36 import org.junit.runner.*;
37 import org.mockito.internal.matchers.apachecommons.ReflectionEquals;
38
39 import javax.annotation.Nonnull;
40 import java.io.ByteArrayInputStream;
41 import java.io.ByteArrayOutputStream;
42 import java.io.IOException;
43 import java.io.InputStream;
44 import java.net.URL;
45
46 import static org.hamcrest.CoreMatchers.*;
47 import static org.junit.Assert.*;
48
49
50
51
52
53
54 @RunWith( Theories.class )
55 public abstract class AbstractSerializerTest2<T> {
56 @Theory
57 public void testSerializer( @Nonnull Entry<T> entry ) throws Exception {
58 Serializer<T> serializer = getSerializer();
59
60
61 byte[] serialized = serialize( serializer, entry.getObject() );
62
63
64 verifySerialized( entry, serialized );
65
66 verifyDeserialized( serializer.deserialize( new ByteArrayInputStream( serialized ) ), entry.getObject() );
67 }
68
69 @Nonnull
70 protected byte[] serialize( @Nonnull Serializer<T> serializer, @Nonnull T objectToSerialize ) throws IOException {
71 ByteArrayOutputStream out = new ByteArrayOutputStream();
72 serializer.serialize( objectToSerialize, out );
73 return out.toByteArray();
74 }
75
76 protected abstract void verifySerialized( @Nonnull Entry<T> entry, @Nonnull byte[] serialized ) throws Exception;
77
78
79
80
81
82
83 @Nonnull
84 protected abstract Serializer<T> getSerializer() throws Exception;
85
86
87
88
89
90
91
92 protected void verifyDeserialized( @Nonnull T deserialized, @Nonnull T original ) {
93 assertEquals( original, deserialized );
94 assertThat( deserialized, is( new ReflectionEquals( original ) ) );
95 }
96
97 @Nonnull
98 public static <T> Entry<? extends T> create( @Nonnull T object, @Nonnull byte[] expected ) {
99 return new Entry<T>( object, expected );
100 }
101
102 @Nonnull
103 public static <T> Entry<? extends T> create( @Nonnull T object, @Nonnull URL expected ) {
104 try {
105 return new Entry<T>( object, IOUtils.toByteArray( expected.openStream() ) );
106 } catch ( IOException e ) {
107 throw new RuntimeException( e );
108 }
109 }
110
111 @Nonnull
112 public static <T> Entry<? extends T> create( @Nonnull T object, @Nonnull InputStream expected ) {
113 try {
114 return new Entry<T>( object, IOUtils.toByteArray( expected ) );
115 } catch ( IOException e ) {
116 throw new RuntimeException( e );
117 }
118 }
119 }