17
package com.google.common.testing;
19
import java.io.Serializable;
20
import junit.framework.AssertionFailedError;
21
import junit.framework.TestCase;
22
import org.checkerframework.checker.nullness.qual.Nullable;
29
public class SerializableTesterTest extends TestCase {
30
public void testStringAssertions() {
31
String original = "hello world";
32
String copy = SerializableTester.reserializeAndAssert(original);
33
assertEquals(original, copy);
34
assertNotSame(original, copy);
37
public void testClassWhichDoesNotImplementEquals() {
38
ClassWhichDoesNotImplementEquals orig = new ClassWhichDoesNotImplementEquals();
39
boolean errorNotThrown = false;
41
SerializableTester.reserializeAndAssert(orig);
42
errorNotThrown = true;
43
} catch (AssertionFailedError error) {
45
assertContains("must be Object#equals to", error.getMessage());
47
assertFalse(errorNotThrown);
50
public void testClassWhichIsAlwaysEqualButHasDifferentHashcodes() {
51
ClassWhichIsAlwaysEqualButHasDifferentHashcodes orig =
52
new ClassWhichIsAlwaysEqualButHasDifferentHashcodes();
53
boolean errorNotThrown = false;
55
SerializableTester.reserializeAndAssert(orig);
56
errorNotThrown = true;
57
} catch (AssertionFailedError error) {
59
assertContains("must be equal to the Object#hashCode", error.getMessage());
61
assertFalse(errorNotThrown);
64
public void testObjectWhichIsEqualButChangesClass() {
65
ObjectWhichIsEqualButChangesClass orig = new ObjectWhichIsEqualButChangesClass();
66
boolean errorNotThrown = false;
68
SerializableTester.reserializeAndAssert(orig);
69
errorNotThrown = true;
70
} catch (AssertionFailedError error) {
72
assertContains("expected:<class ", error.getMessage());
74
assertFalse(errorNotThrown);
77
private static class ClassWhichDoesNotImplementEquals implements Serializable {
78
private static final long serialVersionUID = 1L;
81
private static class ClassWhichIsAlwaysEqualButHasDifferentHashcodes implements Serializable {
82
private static final long serialVersionUID = 2L;
84
@SuppressWarnings("EqualsHashCode")
86
public boolean equals(@Nullable Object other) {
87
return (other instanceof ClassWhichIsAlwaysEqualButHasDifferentHashcodes);
91
private static class ObjectWhichIsEqualButChangesClass implements Serializable {
92
private static final long serialVersionUID = 1L;
95
public boolean equals(@Nullable Object other) {
96
return (other instanceof ObjectWhichIsEqualButChangesClass || other instanceof OtherForm);
100
public int hashCode() {
104
private Object writeReplace() {
105
return new OtherForm();
108
private static class OtherForm implements Serializable {
110
public boolean equals(@Nullable Object other) {
111
return (other instanceof ObjectWhichIsEqualButChangesClass || other instanceof OtherForm);
115
public int hashCode() {
121
private static void assertContains(String expectedSubstring, String actual) {
123
if (!actual.contains(expectedSubstring)) {
124
fail("expected <" + actual + "> to contain <" + expectedSubstring + ">");