1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.functor;
18
19 import static org.junit.Assert.assertEquals;
20 import static org.junit.Assert.assertNotNull;
21 import static org.junit.Assert.assertTrue;
22
23 import java.io.ByteArrayInputStream;
24 import java.io.ByteArrayOutputStream;
25 import java.io.ObjectInputStream;
26 import java.io.ObjectOutputStream;
27 import java.io.Serializable;
28
29 import org.junit.Test;
30
31
32
33
34
35 public abstract class BaseFunctorTest {
36
37
38
39
40 protected abstract Object makeFunctor() throws Exception;
41
42
43
44
45 @Test
46 public final void testObjectEquals() throws Exception {
47 Object obj = makeFunctor();
48 assertEquals("equals must be reflexive",obj,obj);
49 assertEquals("hashCode must be reflexive",obj.hashCode(),obj.hashCode());
50 assertTrue(! obj.equals(null) );
51
52 Object obj2 = makeFunctor();
53 if (obj.equals(obj2)) {
54 assertEquals("equals implies hash equals",obj.hashCode(),obj2.hashCode());
55 assertEquals("equals must be symmetric",obj2,obj);
56 } else {
57 assertTrue("equals must be symmetric",! obj2.equals(obj));
58 }
59 }
60
61 @Test
62 public final void testSerializeDeserializeThenCompare() throws Exception {
63 Object obj = makeFunctor();
64 if (obj instanceof Serializable) {
65 ByteArrayOutputStream buffer = new ByteArrayOutputStream();
66 ObjectOutputStream out = new ObjectOutputStream(buffer);
67 out.writeObject(obj);
68 out.close();
69
70 ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(buffer.toByteArray()));
71 Object dest = in.readObject();
72 in.close();
73 assertEquals("obj != deserialize(serialize(obj))",obj,dest);
74 assertEquals("obj.hash != deserialize(serialize(obj.hash))",obj.hashCode(),dest.hashCode());
75 }
76 }
77
78 @Test
79 public void testToStringIsOverridden() throws Exception {
80 Object obj = makeFunctor();
81 assertNotNull("toString should never return null",obj.toString());
82 assertTrue(
83 obj.getClass().getName() + " should override toString(), found \"" + obj.toString() + "\"",
84 !obj.toString().equals(objectToString(obj)));
85 }
86
87
88
89
90 public static void assertObjectsAreEqual(Object a, Object b) {
91 assertEquals(a,b);
92 assertEquals(b,a);
93 assertEquals(a.hashCode(),b.hashCode());
94 assertEquals(a.toString(),b.toString());
95 }
96
97 public static void assertObjectsAreNotEqual(Object a, Object b) {
98 assertTrue(!a.equals(b));
99 assertTrue(!b.equals(a));
100 assertTrue(a.hashCode() != b.hashCode());
101 assertTrue(!a.toString().equals(b.toString()));
102 }
103
104
105
106 private String objectToString(Object obj) {
107 return obj.getClass().getName() + "@" + Integer.toHexString(obj.hashCode());
108 }
109 }