Add more serialization assertions
[controller.git] / opendaylight / md-sal / cds-access-api / src / test / java / org / opendaylight / controller / cluster / access / concepts / AbstractIdentifierTest.java
1 /*
2  * Copyright (c) 2016 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.controller.cluster.access.concepts;
9
10 import static org.junit.Assert.assertEquals;
11 import static org.junit.Assert.assertFalse;
12 import static org.junit.Assert.assertTrue;
13
14 import java.io.ByteArrayInputStream;
15 import java.io.ByteArrayOutputStream;
16 import java.io.IOException;
17 import java.io.ObjectInputStream;
18 import java.io.ObjectOutputStream;
19 import org.junit.Test;
20 import org.opendaylight.yangtools.concepts.Identifier;
21
22 public abstract class AbstractIdentifierTest<T extends Identifier> {
23     abstract T object();
24
25     abstract T differentObject();
26
27     abstract T equalObject();
28
29     abstract int expectedSize();
30
31     @Test
32     public final void testEquals() {
33         assertTrue(object().equals(object()));
34         assertTrue(object().equals(equalObject()));
35         assertFalse(object().equals(null));
36         assertFalse(object().equals("dummy"));
37         assertFalse(object().equals(differentObject()));
38     }
39
40     @Test
41     public final void testHashCode() {
42         assertEquals(object().hashCode(), equalObject().hashCode());
43     }
44
45
46     @Test
47     public final void testSerialization() throws Exception {
48         assertTrue(object().equals(copy(object())));
49         assertTrue(object().equals(copy(equalObject())));
50         assertFalse(differentObject().equals(copy(object())));
51     }
52
53     @SuppressWarnings("unchecked")
54     private T copy(final T obj) throws IOException, ClassNotFoundException {
55         final ByteArrayOutputStream bos = new ByteArrayOutputStream();
56         try (ObjectOutputStream oos = new ObjectOutputStream(bos)) {
57             oos.writeObject(obj);
58         }
59
60         final byte[] bytes = bos.toByteArray();
61         assertEquals(expectedSize(), bytes.length);
62
63         try (ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes))) {
64             return (T) ois.readObject();
65         }
66     }
67 }