From 2be0ab5e985bcf1b26fac1143e37f987e1684e0a Mon Sep 17 00:00:00 2001 From: maicolAntali Date: Sun, 22 Jan 2023 15:34:39 +0100 Subject: [PATCH 01/14] Port Junit assert to Truth in `com.google.gson.stream` --- .../gson/stream/JsonReaderPathTest.java | 362 ++++++------ .../google/gson/stream/JsonReaderTest.java | 513 +++++++++--------- .../google/gson/stream/JsonWriterTest.java | 118 ++-- 3 files changed, 494 insertions(+), 499 deletions(-) diff --git a/gson/src/test/java/com/google/gson/stream/JsonReaderPathTest.java b/gson/src/test/java/com/google/gson/stream/JsonReaderPathTest.java index a755bd8349..ae6c3f433a 100644 --- a/gson/src/test/java/com/google/gson/stream/JsonReaderPathTest.java +++ b/gson/src/test/java/com/google/gson/stream/JsonReaderPathTest.java @@ -16,7 +16,7 @@ package com.google.gson.stream; -import static org.junit.Assert.assertEquals; +import static com.google.common.truth.Truth.assertThat; import static org.junit.Assume.assumeTrue; import com.google.gson.JsonElement; @@ -46,155 +46,155 @@ public static List parameters() { @Test public void path() throws IOException { JsonReader reader = factory.create("{\"a\":[2,true,false,null,\"b\",{\"c\":\"d\"},[3]]}"); - assertEquals("$", reader.getPreviousPath()); - assertEquals("$", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$"); + assertThat(reader.getPath()).isEqualTo("$"); reader.beginObject(); - assertEquals("$.", reader.getPreviousPath()); - assertEquals("$.", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$."); + assertThat(reader.getPath()).isEqualTo("$."); reader.nextName(); - assertEquals("$.a", reader.getPreviousPath()); - assertEquals("$.a", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$.a"); + assertThat(reader.getPath()).isEqualTo("$.a"); reader.beginArray(); - assertEquals("$.a[0]", reader.getPreviousPath()); - assertEquals("$.a[0]", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$.a[0]"); + assertThat(reader.getPath()).isEqualTo("$.a[0]"); reader.nextInt(); - assertEquals("$.a[0]", reader.getPreviousPath()); - assertEquals("$.a[1]", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$.a[0]"); + assertThat(reader.getPath()).isEqualTo("$.a[1]"); reader.nextBoolean(); - assertEquals("$.a[1]", reader.getPreviousPath()); - assertEquals("$.a[2]", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$.a[1]"); + assertThat(reader.getPath()).isEqualTo("$.a[2]"); reader.nextBoolean(); - assertEquals("$.a[2]", reader.getPreviousPath()); - assertEquals("$.a[3]", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$.a[2]"); + assertThat(reader.getPath()).isEqualTo("$.a[3]"); reader.nextNull(); - assertEquals("$.a[3]", reader.getPreviousPath()); - assertEquals("$.a[4]", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$.a[3]"); + assertThat(reader.getPath()).isEqualTo("$.a[4]"); reader.nextString(); - assertEquals("$.a[4]", reader.getPreviousPath()); - assertEquals("$.a[5]", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$.a[4]"); + assertThat(reader.getPath()).isEqualTo("$.a[5]"); reader.beginObject(); - assertEquals("$.a[5].", reader.getPreviousPath()); - assertEquals("$.a[5].", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$.a[5]."); + assertThat(reader.getPath()).isEqualTo("$.a[5]."); reader.nextName(); - assertEquals("$.a[5].c", reader.getPreviousPath()); - assertEquals("$.a[5].c", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$.a[5].c"); + assertThat(reader.getPath()).isEqualTo("$.a[5].c"); reader.nextString(); - assertEquals("$.a[5].c", reader.getPreviousPath()); - assertEquals("$.a[5].c", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$.a[5].c"); + assertThat(reader.getPath()).isEqualTo("$.a[5].c"); reader.endObject(); - assertEquals("$.a[5]", reader.getPreviousPath()); - assertEquals("$.a[6]", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$.a[5]"); + assertThat(reader.getPath()).isEqualTo("$.a[6]"); reader.beginArray(); - assertEquals("$.a[6][0]", reader.getPreviousPath()); - assertEquals("$.a[6][0]", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$.a[6][0]"); + assertThat(reader.getPath()).isEqualTo("$.a[6][0]"); reader.nextInt(); - assertEquals("$.a[6][0]", reader.getPreviousPath()); - assertEquals("$.a[6][1]", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$.a[6][0]"); + assertThat(reader.getPath()).isEqualTo("$.a[6][1]"); reader.endArray(); - assertEquals("$.a[6]", reader.getPreviousPath()); - assertEquals("$.a[7]", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$.a[6]"); + assertThat(reader.getPath()).isEqualTo("$.a[7]"); reader.endArray(); - assertEquals("$.a", reader.getPreviousPath()); - assertEquals("$.a", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$.a"); + assertThat(reader.getPath()).isEqualTo("$.a"); reader.endObject(); - assertEquals("$", reader.getPreviousPath()); - assertEquals("$", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$"); + assertThat(reader.getPath()).isEqualTo("$"); } @Test public void objectPath() throws IOException { JsonReader reader = factory.create("{\"a\":1,\"b\":2}"); - assertEquals("$", reader.getPreviousPath()); - assertEquals("$", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$"); + assertThat(reader.getPath()).isEqualTo("$"); reader.peek(); - assertEquals("$", reader.getPreviousPath()); - assertEquals("$", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$"); + assertThat(reader.getPath()).isEqualTo("$"); reader.beginObject(); - assertEquals("$.", reader.getPreviousPath()); - assertEquals("$.", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$."); + assertThat(reader.getPath()).isEqualTo("$."); reader.peek(); - assertEquals("$.", reader.getPreviousPath()); - assertEquals("$.", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$."); + assertThat(reader.getPath()).isEqualTo("$."); reader.nextName(); - assertEquals("$.a", reader.getPreviousPath()); - assertEquals("$.a", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$.a"); + assertThat(reader.getPath()).isEqualTo("$.a"); reader.peek(); - assertEquals("$.a", reader.getPreviousPath()); - assertEquals("$.a", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$.a"); + assertThat(reader.getPath()).isEqualTo("$.a"); reader.nextInt(); - assertEquals("$.a", reader.getPreviousPath()); - assertEquals("$.a", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$.a"); + assertThat(reader.getPath()).isEqualTo("$.a"); reader.peek(); - assertEquals("$.a", reader.getPreviousPath()); - assertEquals("$.a", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$.a"); + assertThat(reader.getPath()).isEqualTo("$.a"); reader.nextName(); - assertEquals("$.b", reader.getPreviousPath()); - assertEquals("$.b", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$.b"); + assertThat(reader.getPath()).isEqualTo("$.b"); reader.peek(); - assertEquals("$.b", reader.getPreviousPath()); - assertEquals("$.b", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$.b"); + assertThat(reader.getPath()).isEqualTo("$.b"); reader.nextInt(); - assertEquals("$.b", reader.getPreviousPath()); - assertEquals("$.b", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$.b"); + assertThat(reader.getPath()).isEqualTo("$.b"); reader.peek(); - assertEquals("$.b", reader.getPreviousPath()); - assertEquals("$.b", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$.b"); + assertThat(reader.getPath()).isEqualTo("$.b"); reader.endObject(); - assertEquals("$", reader.getPreviousPath()); - assertEquals("$", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$"); + assertThat(reader.getPath()).isEqualTo("$"); reader.peek(); - assertEquals("$", reader.getPreviousPath()); - assertEquals("$", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$"); + assertThat(reader.getPath()).isEqualTo("$"); reader.close(); - assertEquals("$", reader.getPreviousPath()); - assertEquals("$", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$"); + assertThat(reader.getPath()).isEqualTo("$"); } @Test public void arrayPath() throws IOException { JsonReader reader = factory.create("[1,2]"); - assertEquals("$", reader.getPreviousPath()); - assertEquals("$", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$"); + assertThat(reader.getPath()).isEqualTo("$"); reader.peek(); - assertEquals("$", reader.getPreviousPath()); - assertEquals("$", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$"); + assertThat(reader.getPath()).isEqualTo("$"); reader.beginArray(); - assertEquals("$[0]", reader.getPreviousPath()); - assertEquals("$[0]", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$[0]"); + assertThat(reader.getPath()).isEqualTo("$[0]"); reader.peek(); - assertEquals("$[0]", reader.getPreviousPath()); - assertEquals("$[0]", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$[0]"); + assertThat(reader.getPath()).isEqualTo("$[0]"); reader.nextInt(); - assertEquals("$[0]", reader.getPreviousPath()); - assertEquals("$[1]", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$[0]"); + assertThat(reader.getPath()).isEqualTo("$[1]"); reader.peek(); - assertEquals("$[0]", reader.getPreviousPath()); - assertEquals("$[1]", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$[0]"); + assertThat(reader.getPath()).isEqualTo("$[1]"); reader.nextInt(); - assertEquals("$[1]", reader.getPreviousPath()); - assertEquals("$[2]", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$[1]"); + assertThat(reader.getPath()).isEqualTo("$[2]"); reader.peek(); - assertEquals("$[1]", reader.getPreviousPath()); - assertEquals("$[2]", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$[1]"); + assertThat(reader.getPath()).isEqualTo("$[2]"); reader.endArray(); - assertEquals("$", reader.getPreviousPath()); - assertEquals("$", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$"); + assertThat(reader.getPath()).isEqualTo("$"); reader.peek(); - assertEquals("$", reader.getPreviousPath()); - assertEquals("$", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$"); + assertThat(reader.getPath()).isEqualTo("$"); reader.close(); - assertEquals("$", reader.getPreviousPath()); - assertEquals("$", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$"); + assertThat(reader.getPath()).isEqualTo("$"); } @Test public void multipleTopLevelValuesInOneDocument() throws IOException { @@ -204,12 +204,12 @@ public static List parameters() { reader.setLenient(true); reader.beginArray(); reader.endArray(); - assertEquals("$", reader.getPreviousPath()); - assertEquals("$", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$"); + assertThat(reader.getPath()).isEqualTo("$"); reader.beginArray(); reader.endArray(); - assertEquals("$", reader.getPreviousPath()); - assertEquals("$", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$"); + assertThat(reader.getPath()).isEqualTo("$"); } @Test public void skipArrayElements() throws IOException { @@ -217,45 +217,45 @@ public static List parameters() { reader.beginArray(); reader.skipValue(); reader.skipValue(); - assertEquals("$[1]", reader.getPreviousPath()); - assertEquals("$[2]", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$[1]"); + assertThat(reader.getPath()).isEqualTo("$[2]"); } @Test public void skipArrayEnd() throws IOException { JsonReader reader = factory.create("[[],1]"); reader.beginArray(); reader.beginArray(); - assertEquals("$[0][0]", reader.getPreviousPath()); - assertEquals("$[0][0]", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$[0][0]"); + assertThat(reader.getPath()).isEqualTo("$[0][0]"); reader.skipValue(); // skip end of array - assertEquals("$[0]", reader.getPreviousPath()); - assertEquals("$[1]", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$[0]"); + assertThat(reader.getPath()).isEqualTo("$[1]"); } @Test public void skipObjectNames() throws IOException { JsonReader reader = factory.create("{\"a\":[]}"); reader.beginObject(); reader.skipValue(); - assertEquals("$.", reader.getPreviousPath()); - assertEquals("$.", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$."); + assertThat(reader.getPath()).isEqualTo("$."); reader.beginArray(); - assertEquals("$.[0]", reader.getPreviousPath()); - assertEquals("$.[0]", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$.[0]"); + assertThat(reader.getPath()).isEqualTo("$.[0]"); } @Test public void skipObjectValues() throws IOException { JsonReader reader = factory.create("{\"a\":1,\"b\":2}"); reader.beginObject(); - assertEquals("$.", reader.getPreviousPath()); - assertEquals("$.", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$."); + assertThat(reader.getPath()).isEqualTo("$."); reader.nextName(); reader.skipValue(); - assertEquals("$.a", reader.getPreviousPath()); - assertEquals("$.a", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$.a"); + assertThat(reader.getPath()).isEqualTo("$.a"); reader.nextName(); - assertEquals("$.b", reader.getPreviousPath()); - assertEquals("$.b", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$.b"); + assertThat(reader.getPath()).isEqualTo("$.b"); } @Test public void skipObjectEnd() throws IOException { @@ -263,135 +263,135 @@ public static List parameters() { reader.beginObject(); reader.nextName(); reader.beginObject(); - assertEquals("$.a.", reader.getPreviousPath()); - assertEquals("$.a.", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$.a."); + assertThat(reader.getPath()).isEqualTo("$.a."); reader.skipValue(); // skip end of object - assertEquals("$.a", reader.getPreviousPath()); - assertEquals("$.a", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$.a"); + assertThat(reader.getPath()).isEqualTo("$.a"); } @Test public void skipNestedStructures() throws IOException { JsonReader reader = factory.create("[[1,2,3],4]"); reader.beginArray(); reader.skipValue(); - assertEquals("$[0]", reader.getPreviousPath()); - assertEquals("$[1]", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$[0]"); + assertThat(reader.getPath()).isEqualTo("$[1]"); } @Test public void skipEndOfDocument() throws IOException { JsonReader reader = factory.create("[]"); reader.beginArray(); reader.endArray(); - assertEquals("$", reader.getPreviousPath()); - assertEquals("$", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$"); + assertThat(reader.getPath()).isEqualTo("$"); reader.skipValue(); - assertEquals("$", reader.getPreviousPath()); - assertEquals("$", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$"); + assertThat(reader.getPath()).isEqualTo("$"); reader.skipValue(); - assertEquals("$", reader.getPreviousPath()); - assertEquals("$", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$"); + assertThat(reader.getPath()).isEqualTo("$"); } @Test public void arrayOfObjects() throws IOException { JsonReader reader = factory.create("[{},{},{}]"); reader.beginArray(); - assertEquals("$[0]", reader.getPreviousPath()); - assertEquals("$[0]", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$[0]"); + assertThat(reader.getPath()).isEqualTo("$[0]"); reader.beginObject(); - assertEquals("$[0].", reader.getPreviousPath()); - assertEquals("$[0].", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$[0]."); + assertThat(reader.getPath()).isEqualTo("$[0]."); reader.endObject(); - assertEquals("$[0]", reader.getPreviousPath()); - assertEquals("$[1]", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$[0]"); + assertThat(reader.getPath()).isEqualTo("$[1]"); reader.beginObject(); - assertEquals("$[1].", reader.getPreviousPath()); - assertEquals("$[1].", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$[1]."); + assertThat(reader.getPath()).isEqualTo("$[1]."); reader.endObject(); - assertEquals("$[1]", reader.getPreviousPath()); - assertEquals("$[2]", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$[1]"); + assertThat(reader.getPath()).isEqualTo("$[2]"); reader.beginObject(); - assertEquals("$[2].", reader.getPreviousPath()); - assertEquals("$[2].", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$[2]."); + assertThat(reader.getPath()).isEqualTo("$[2]."); reader.endObject(); - assertEquals("$[2]", reader.getPreviousPath()); - assertEquals("$[3]", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$[2]"); + assertThat(reader.getPath()).isEqualTo("$[3]"); reader.endArray(); - assertEquals("$", reader.getPreviousPath()); - assertEquals("$", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$"); + assertThat(reader.getPath()).isEqualTo("$"); } @Test public void arrayOfArrays() throws IOException { JsonReader reader = factory.create("[[],[],[]]"); reader.beginArray(); - assertEquals("$[0]", reader.getPreviousPath()); - assertEquals("$[0]", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$[0]"); + assertThat(reader.getPath()).isEqualTo("$[0]"); reader.beginArray(); - assertEquals("$[0][0]", reader.getPreviousPath()); - assertEquals("$[0][0]", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$[0][0]"); + assertThat(reader.getPath()).isEqualTo("$[0][0]"); reader.endArray(); - assertEquals("$[0]", reader.getPreviousPath()); - assertEquals("$[1]", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$[0]"); + assertThat(reader.getPath()).isEqualTo("$[1]"); reader.beginArray(); - assertEquals("$[1][0]", reader.getPreviousPath()); - assertEquals("$[1][0]", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$[1][0]"); + assertThat(reader.getPath()).isEqualTo("$[1][0]"); reader.endArray(); - assertEquals("$[1]", reader.getPreviousPath()); - assertEquals("$[2]", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$[1]"); + assertThat(reader.getPath()).isEqualTo("$[2]"); reader.beginArray(); - assertEquals("$[2][0]", reader.getPreviousPath()); - assertEquals("$[2][0]", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$[2][0]"); + assertThat(reader.getPath()).isEqualTo("$[2][0]"); reader.endArray(); - assertEquals("$[2]", reader.getPreviousPath()); - assertEquals("$[3]", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$[2]"); + assertThat(reader.getPath()).isEqualTo("$[3]"); reader.endArray(); - assertEquals("$", reader.getPreviousPath()); - assertEquals("$", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$"); + assertThat(reader.getPath()).isEqualTo("$"); } @Test public void objectOfObjects() throws IOException { JsonReader reader = factory.create("{\"a\":{\"a1\":1,\"a2\":2},\"b\":{\"b1\":1}}"); reader.beginObject(); - assertEquals("$.", reader.getPreviousPath()); - assertEquals("$.", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$."); + assertThat(reader.getPath()).isEqualTo("$."); reader.nextName(); - assertEquals("$.a", reader.getPreviousPath()); - assertEquals("$.a", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$.a"); + assertThat(reader.getPath()).isEqualTo("$.a"); reader.beginObject(); - assertEquals("$.a.", reader.getPreviousPath()); - assertEquals("$.a.", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$.a."); + assertThat(reader.getPath()).isEqualTo("$.a."); reader.nextName(); - assertEquals("$.a.a1", reader.getPreviousPath()); - assertEquals("$.a.a1", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$.a.a1"); + assertThat(reader.getPath()).isEqualTo("$.a.a1"); reader.nextInt(); - assertEquals("$.a.a1", reader.getPreviousPath()); - assertEquals("$.a.a1", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$.a.a1"); + assertThat(reader.getPath()).isEqualTo("$.a.a1"); reader.nextName(); - assertEquals("$.a.a2", reader.getPreviousPath()); - assertEquals("$.a.a2", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$.a.a2"); + assertThat(reader.getPath()).isEqualTo("$.a.a2"); reader.nextInt(); - assertEquals("$.a.a2", reader.getPreviousPath()); - assertEquals("$.a.a2", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$.a.a2"); + assertThat(reader.getPath()).isEqualTo("$.a.a2"); reader.endObject(); - assertEquals("$.a", reader.getPreviousPath()); - assertEquals("$.a", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$.a"); + assertThat(reader.getPath()).isEqualTo("$.a"); reader.nextName(); - assertEquals("$.b", reader.getPreviousPath()); - assertEquals("$.b", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$.b"); + assertThat(reader.getPath()).isEqualTo("$.b"); reader.beginObject(); - assertEquals("$.b.", reader.getPreviousPath()); - assertEquals("$.b.", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$.b."); + assertThat(reader.getPath()).isEqualTo("$.b."); reader.nextName(); - assertEquals("$.b.b1", reader.getPreviousPath()); - assertEquals("$.b.b1", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$.b.b1"); + assertThat(reader.getPath()).isEqualTo("$.b.b1"); reader.nextInt(); - assertEquals("$.b.b1", reader.getPreviousPath()); - assertEquals("$.b.b1", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$.b.b1"); + assertThat(reader.getPath()).isEqualTo("$.b.b1"); reader.endObject(); - assertEquals("$.b", reader.getPreviousPath()); - assertEquals("$.b", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$.b"); + assertThat(reader.getPath()).isEqualTo("$.b"); reader.endObject(); - assertEquals("$", reader.getPreviousPath()); - assertEquals("$", reader.getPath()); + assertThat(reader.getPreviousPath()).isEqualTo("$"); + assertThat(reader.getPath()).isEqualTo("$"); } public enum Factory { diff --git a/gson/src/test/java/com/google/gson/stream/JsonReaderTest.java b/gson/src/test/java/com/google/gson/stream/JsonReaderTest.java index e4ce428a0c..92af5bd122 100644 --- a/gson/src/test/java/com/google/gson/stream/JsonReaderTest.java +++ b/gson/src/test/java/com/google/gson/stream/JsonReaderTest.java @@ -25,9 +25,7 @@ import static com.google.gson.stream.JsonToken.NULL; import static com.google.gson.stream.JsonToken.NUMBER; import static com.google.gson.stream.JsonToken.STRING; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.fail; import java.io.EOFException; @@ -44,19 +42,19 @@ public final class JsonReaderTest { public void testReadArray() throws IOException { JsonReader reader = new JsonReader(reader("[true, true]")); reader.beginArray(); - assertEquals(true, reader.nextBoolean()); - assertEquals(true, reader.nextBoolean()); + assertThat(reader.nextBoolean()).isTrue(); + assertThat(reader.nextBoolean()).isTrue(); reader.endArray(); - assertEquals(JsonToken.END_DOCUMENT, reader.peek()); + assertThat(reader.peek()).isEqualTo(JsonToken.END_DOCUMENT); } @Test public void testReadEmptyArray() throws IOException { JsonReader reader = new JsonReader(reader("[]")); reader.beginArray(); - assertFalse(reader.hasNext()); + assertThat(reader.hasNext()).isFalse(); reader.endArray(); - assertEquals(JsonToken.END_DOCUMENT, reader.peek()); + assertThat(reader.peek()).isEqualTo(JsonToken.END_DOCUMENT); } @Test @@ -64,21 +62,21 @@ public void testReadObject() throws IOException { JsonReader reader = new JsonReader(reader( "{\"a\": \"android\", \"b\": \"banana\"}")); reader.beginObject(); - assertEquals("a", reader.nextName()); - assertEquals("android", reader.nextString()); - assertEquals("b", reader.nextName()); - assertEquals("banana", reader.nextString()); + assertThat(reader.nextName()).isEqualTo("a"); + assertThat(reader.nextString()).isEqualTo("android"); + assertThat(reader.nextName()).isEqualTo("b"); + assertThat(reader.nextString()).isEqualTo("banana"); reader.endObject(); - assertEquals(JsonToken.END_DOCUMENT, reader.peek()); + assertThat(reader.peek()).isEqualTo(JsonToken.END_DOCUMENT); } @Test public void testReadEmptyObject() throws IOException { JsonReader reader = new JsonReader(reader("{}")); reader.beginObject(); - assertFalse(reader.hasNext()); + assertThat(reader.hasNext()).isFalse(); reader.endObject(); - assertEquals(JsonToken.END_DOCUMENT, reader.peek()); + assertThat(reader.peek()).isEqualTo(JsonToken.END_DOCUMENT); } @Test @@ -86,7 +84,7 @@ public void testHasNextEndOfDocument() throws IOException { JsonReader reader = new JsonReader(reader("{}")); reader.beginObject(); reader.endObject(); - assertFalse(reader.hasNext()); + assertThat(reader.hasNext()).isFalse(); } @Test @@ -94,12 +92,12 @@ public void testSkipArray() throws IOException { JsonReader reader = new JsonReader(reader( "{\"a\": [\"one\", \"two\", \"three\"], \"b\": 123}")); reader.beginObject(); - assertEquals("a", reader.nextName()); + assertThat(reader.nextName()).isEqualTo("a"); reader.skipValue(); - assertEquals("b", reader.nextName()); - assertEquals(123, reader.nextInt()); + assertThat(reader.nextName()).isEqualTo("b"); + assertThat(reader.nextInt()).isEqualTo(123); reader.endObject(); - assertEquals(JsonToken.END_DOCUMENT, reader.peek()); + assertThat(reader.peek()).isEqualTo(JsonToken.END_DOCUMENT); } @Test @@ -107,13 +105,13 @@ public void testSkipArrayAfterPeek() throws Exception { JsonReader reader = new JsonReader(reader( "{\"a\": [\"one\", \"two\", \"three\"], \"b\": 123}")); reader.beginObject(); - assertEquals("a", reader.nextName()); - assertEquals(BEGIN_ARRAY, reader.peek()); + assertThat(reader.nextName()).isEqualTo("a"); + assertThat(reader.peek()).isEqualTo(BEGIN_ARRAY); reader.skipValue(); - assertEquals("b", reader.nextName()); - assertEquals(123, reader.nextInt()); + assertThat(reader.nextName()).isEqualTo("b"); + assertThat(reader.nextInt()).isEqualTo(123); reader.endObject(); - assertEquals(JsonToken.END_DOCUMENT, reader.peek()); + assertThat(reader.peek()).isEqualTo(JsonToken.END_DOCUMENT); } @Test @@ -121,7 +119,7 @@ public void testSkipTopLevelObject() throws Exception { JsonReader reader = new JsonReader(reader( "{\"a\": [\"one\", \"two\", \"three\"], \"b\": 123}")); reader.skipValue(); - assertEquals(JsonToken.END_DOCUMENT, reader.peek()); + assertThat(reader.peek()).isEqualTo(JsonToken.END_DOCUMENT); } @Test @@ -129,12 +127,12 @@ public void testSkipObject() throws IOException { JsonReader reader = new JsonReader(reader( "{\"a\": { \"c\": [], \"d\": [true, true, {}] }, \"b\": \"banana\"}")); reader.beginObject(); - assertEquals("a", reader.nextName()); + assertThat(reader.nextName()).isEqualTo("a"); reader.skipValue(); - assertEquals("b", reader.nextName()); + assertThat(reader.nextName()).isEqualTo("b"); reader.skipValue(); reader.endObject(); - assertEquals(JsonToken.END_DOCUMENT, reader.peek()); + assertThat(reader.peek()).isEqualTo(JsonToken.END_DOCUMENT); } @Test @@ -143,16 +141,16 @@ public void testSkipObjectAfterPeek() throws Exception { + ", \"two\": { \"num\": 2 }" + ", \"three\": { \"num\": 3 }" + "}"; JsonReader reader = new JsonReader(reader(json)); reader.beginObject(); - assertEquals("one", reader.nextName()); - assertEquals(BEGIN_OBJECT, reader.peek()); + assertThat(reader.nextName()).isEqualTo("one"); + assertThat(reader.peek()).isEqualTo(BEGIN_OBJECT); reader.skipValue(); - assertEquals("two", reader.nextName()); - assertEquals(BEGIN_OBJECT, reader.peek()); + assertThat(reader.nextName()).isEqualTo("two"); + assertThat(reader.peek()).isEqualTo(BEGIN_OBJECT); reader.skipValue(); - assertEquals("three", reader.nextName()); + assertThat(reader.nextName()).isEqualTo("three"); reader.skipValue(); reader.endObject(); - assertEquals(JsonToken.END_DOCUMENT, reader.peek()); + assertThat(reader.peek()).isEqualTo(JsonToken.END_DOCUMENT); } @Test @@ -160,9 +158,9 @@ public void testSkipObjectName() throws IOException { JsonReader reader = new JsonReader(reader("{\"a\": 1}")); reader.beginObject(); reader.skipValue(); - assertEquals(JsonToken.NUMBER, reader.peek()); - assertEquals("$.", reader.getPath()); - assertEquals(1, reader.nextInt()); + assertThat(reader.peek()).isEqualTo(JsonToken.NUMBER); + assertThat(reader.getPath()).isEqualTo("$."); + assertThat(reader.nextInt()).isEqualTo(1); } @Test @@ -171,9 +169,9 @@ public void testSkipObjectNameSingleQuoted() throws IOException { reader.setLenient(true); reader.beginObject(); reader.skipValue(); - assertEquals(JsonToken.NUMBER, reader.peek()); - assertEquals("$.", reader.getPath()); - assertEquals(1, reader.nextInt()); + assertThat(reader.peek()).isEqualTo(JsonToken.NUMBER); + assertThat(reader.getPath()).isEqualTo("$."); + assertThat(reader.nextInt()).isEqualTo(1); } @Test @@ -182,9 +180,9 @@ public void testSkipObjectNameUnquoted() throws IOException { reader.setLenient(true); reader.beginObject(); reader.skipValue(); - assertEquals(JsonToken.NUMBER, reader.peek()); - assertEquals("$.", reader.getPath()); - assertEquals(1, reader.nextInt()); + assertThat(reader.peek()).isEqualTo(JsonToken.NUMBER); + assertThat(reader.getPath()).isEqualTo("$."); + assertThat(reader.nextInt()).isEqualTo(1); } @Test @@ -192,12 +190,12 @@ public void testSkipInteger() throws IOException { JsonReader reader = new JsonReader(reader( "{\"a\":123456789,\"b\":-123456789}")); reader.beginObject(); - assertEquals("a", reader.nextName()); + assertThat(reader.nextName()).isEqualTo("a"); reader.skipValue(); - assertEquals("b", reader.nextName()); + assertThat(reader.nextName()).isEqualTo("b"); reader.skipValue(); reader.endObject(); - assertEquals(JsonToken.END_DOCUMENT, reader.peek()); + assertThat(reader.peek()).isEqualTo(JsonToken.END_DOCUMENT); } @Test @@ -205,12 +203,12 @@ public void testSkipDouble() throws IOException { JsonReader reader = new JsonReader(reader( "{\"a\":-123.456e-789,\"b\":123456789.0}")); reader.beginObject(); - assertEquals("a", reader.nextName()); + assertThat(reader.nextName()).isEqualTo("a"); reader.skipValue(); - assertEquals("b", reader.nextName()); + assertThat(reader.nextName()).isEqualTo("b"); reader.skipValue(); reader.endObject(); - assertEquals(JsonToken.END_DOCUMENT, reader.peek()); + assertThat(reader.peek()).isEqualTo(JsonToken.END_DOCUMENT); } @Test @@ -218,12 +216,12 @@ public void testSkipValueAfterEndOfDocument() throws IOException { JsonReader reader = new JsonReader(reader("{}")); reader.beginObject(); reader.endObject(); - assertEquals(JsonToken.END_DOCUMENT, reader.peek()); + assertThat(reader.peek()).isEqualTo(JsonToken.END_DOCUMENT); - assertEquals("$", reader.getPath()); + assertThat(reader.getPath()).isEqualTo("$"); reader.skipValue(); - assertEquals(JsonToken.END_DOCUMENT, reader.peek()); - assertEquals("$", reader.getPath()); + assertThat(reader.peek()).isEqualTo(JsonToken.END_DOCUMENT); + assertThat(reader.getPath()).isEqualTo("$"); } @Test @@ -231,8 +229,8 @@ public void testSkipValueAtArrayEnd() throws IOException { JsonReader reader = new JsonReader(reader("[]")); reader.beginArray(); reader.skipValue(); - assertEquals(JsonToken.END_DOCUMENT, reader.peek()); - assertEquals("$", reader.getPath()); + assertThat(reader.peek()).isEqualTo(JsonToken.END_DOCUMENT); + assertThat(reader.getPath()).isEqualTo("$"); } @Test @@ -240,8 +238,8 @@ public void testSkipValueAtObjectEnd() throws IOException { JsonReader reader = new JsonReader(reader("{}")); reader.beginObject(); reader.skipValue(); - assertEquals(JsonToken.END_DOCUMENT, reader.peek()); - assertEquals("$", reader.getPath()); + assertThat(reader.peek()).isEqualTo(JsonToken.END_DOCUMENT); + assertThat(reader.getPath()).isEqualTo("$"); } @Test @@ -252,14 +250,14 @@ public void testHelloWorld() throws IOException { "}"; JsonReader reader = new JsonReader(reader(json)); reader.beginObject(); - assertEquals("hello", reader.nextName()); - assertEquals(true, reader.nextBoolean()); - assertEquals("foo", reader.nextName()); + assertThat(reader.nextName()).isEqualTo("hello"); + assertThat(reader.nextBoolean()).isTrue(); + assertThat(reader.nextName()).isEqualTo("foo"); reader.beginArray(); - assertEquals("world", reader.nextString()); + assertThat(reader.nextString()).isEqualTo("world"); reader.endArray(); reader.endObject(); - assertEquals(JsonToken.END_DOCUMENT, reader.peek()); + assertThat(reader.peek()).isEqualTo(JsonToken.END_DOCUMENT); } @Test @@ -326,27 +324,27 @@ public void testCharacterUnescaping() throws IOException { + "]"; JsonReader reader = new JsonReader(reader(json)); reader.beginArray(); - assertEquals("a", reader.nextString()); - assertEquals("a\"", reader.nextString()); - assertEquals("\"", reader.nextString()); - assertEquals(":", reader.nextString()); - assertEquals(",", reader.nextString()); - assertEquals("\b", reader.nextString()); - assertEquals("\f", reader.nextString()); - assertEquals("\n", reader.nextString()); - assertEquals("\r", reader.nextString()); - assertEquals("\t", reader.nextString()); - assertEquals(" ", reader.nextString()); - assertEquals("\\", reader.nextString()); - assertEquals("{", reader.nextString()); - assertEquals("}", reader.nextString()); - assertEquals("[", reader.nextString()); - assertEquals("]", reader.nextString()); - assertEquals("\0", reader.nextString()); - assertEquals("\u0019", reader.nextString()); - assertEquals("\u20AC", reader.nextString()); + assertThat(reader.nextString()).isEqualTo("a"); + assertThat(reader.nextString()).isEqualTo("a\""); + assertThat(reader.nextString()).isEqualTo("\""); + assertThat(reader.nextString()).isEqualTo(":"); + assertThat(reader.nextString()).isEqualTo(","); + assertThat(reader.nextString()).isEqualTo("\b"); + assertThat(reader.nextString()).isEqualTo("\f"); + assertThat(reader.nextString()).isEqualTo("\n"); + assertThat(reader.nextString()).isEqualTo("\r"); + assertThat(reader.nextString()).isEqualTo("\t"); + assertThat(reader.nextString()).isEqualTo(" "); + assertThat(reader.nextString()).isEqualTo("\\"); + assertThat(reader.nextString()).isEqualTo("{"); + assertThat(reader.nextString()).isEqualTo("}"); + assertThat(reader.nextString()).isEqualTo("["); + assertThat(reader.nextString()).isEqualTo("]"); + assertThat(reader.nextString()).isEqualTo("\0"); + assertThat(reader.nextString()).isEqualTo("\u0019"); + assertThat(reader.nextString()).isEqualTo("\u20AC"); reader.endArray(); - assertEquals(JsonToken.END_DOCUMENT, reader.peek()); + assertThat(reader.peek()).isEqualTo(JsonToken.END_DOCUMENT); } @Test @@ -389,9 +387,9 @@ public void testUnescapingTruncatedSequence() throws IOException { public void testIntegersWithFractionalPartSpecified() throws IOException { JsonReader reader = new JsonReader(reader("[1.0,1.0,1.0]")); reader.beginArray(); - assertEquals(1.0, reader.nextDouble(), 0); - assertEquals(1, reader.nextInt()); - assertEquals(1L, reader.nextLong()); + assertThat(reader.nextDouble()).isEqualTo(1.0); + assertThat(reader.nextInt()).isEqualTo(1); + assertThat(reader.nextLong()).isEqualTo(1L); } @Test @@ -416,26 +414,26 @@ public void testDoubles() throws IOException { + "1e+1]"; JsonReader reader = new JsonReader(reader(json)); reader.beginArray(); - assertEquals(-0.0, reader.nextDouble(), 0); - assertEquals(1.0, reader.nextDouble(), 0); - assertEquals(1.7976931348623157E308, reader.nextDouble(), 0); - assertEquals(4.9E-324, reader.nextDouble(), 0); - assertEquals(0.0, reader.nextDouble(), 0); - assertEquals(0.0, reader.nextDouble(), 0); - assertEquals(-0.5, reader.nextDouble(), 0); - assertEquals(2.2250738585072014E-308, reader.nextDouble(), 0); - assertEquals(3.141592653589793, reader.nextDouble(), 0); - assertEquals(2.718281828459045, reader.nextDouble(), 0); - assertEquals(0.0, reader.nextDouble(), 0); - assertEquals(0.01, reader.nextDouble(), 0); - assertEquals(0.0, reader.nextDouble(), 0); - assertEquals(1.0, reader.nextDouble(), 0); - assertEquals(1.0, reader.nextDouble(), 0); - assertEquals(1.0, reader.nextDouble(), 0); - assertEquals(10.0, reader.nextDouble(), 0); - assertEquals(10.0, reader.nextDouble(), 0); + assertThat(reader.nextDouble()).isEqualTo(-0.0); + assertThat(reader.nextDouble()).isEqualTo(1.0); + assertThat(reader.nextDouble()).isEqualTo(1.7976931348623157E308); + assertThat(reader.nextDouble()).isEqualTo(4.9E-324); + assertThat(reader.nextDouble()).isEqualTo(0.0); + assertThat(reader.nextDouble()).isEqualTo(0.0); + assertThat(reader.nextDouble()).isEqualTo(-0.5); + assertThat(reader.nextDouble()).isEqualTo(2.2250738585072014E-308); + assertThat(reader.nextDouble()).isEqualTo(3.141592653589793); + assertThat(reader.nextDouble()).isEqualTo(2.718281828459045); + assertThat(reader.nextDouble()).isEqualTo(0.0); + assertThat(reader.nextDouble()).isEqualTo(0.01); + assertThat(reader.nextDouble()).isEqualTo(0.0); + assertThat(reader.nextDouble()).isEqualTo(1.0); + assertThat(reader.nextDouble()).isEqualTo(1.0); + assertThat(reader.nextDouble()).isEqualTo(1.0); + assertThat(reader.nextDouble()).isEqualTo(10.0); + assertThat(reader.nextDouble()).isEqualTo(10.0); reader.endArray(); - assertEquals(JsonToken.END_DOCUMENT, reader.peek()); + assertThat(reader.peek()).isEqualTo(JsonToken.END_DOCUMENT); } @Test @@ -468,9 +466,9 @@ public void testLenientNonFiniteDoubles() throws IOException { JsonReader reader = new JsonReader(reader(json)); reader.setLenient(true); reader.beginArray(); - assertTrue(Double.isNaN(reader.nextDouble())); - assertEquals(Double.NEGATIVE_INFINITY, reader.nextDouble(), 0); - assertEquals(Double.POSITIVE_INFINITY, reader.nextDouble(), 0); + assertThat(Double.isNaN(reader.nextDouble())).isTrue(); + assertThat(reader.nextDouble()).isEqualTo(Double.NEGATIVE_INFINITY); + assertThat(reader.nextDouble()).isEqualTo(Double.POSITIVE_INFINITY); reader.endArray(); } @@ -480,9 +478,9 @@ public void testLenientQuotedNonFiniteDoubles() throws IOException { JsonReader reader = new JsonReader(reader(json)); reader.setLenient(true); reader.beginArray(); - assertTrue(Double.isNaN(reader.nextDouble())); - assertEquals(Double.NEGATIVE_INFINITY, reader.nextDouble(), 0); - assertEquals(Double.POSITIVE_INFINITY, reader.nextDouble(), 0); + assertThat(Double.isNaN(reader.nextDouble())).isTrue(); + assertThat(reader.nextDouble()).isEqualTo(Double.NEGATIVE_INFINITY); + assertThat(reader.nextDouble()).isEqualTo(Double.POSITIVE_INFINITY); reader.endArray(); } @@ -507,29 +505,29 @@ public void testLongs() throws IOException { + "9223372036854775807]"; JsonReader reader = new JsonReader(reader(json)); reader.beginArray(); - assertEquals(0L, reader.nextLong()); - assertEquals(0, reader.nextInt()); - assertEquals(0.0, reader.nextDouble(), 0); - assertEquals(1L, reader.nextLong()); - assertEquals(1, reader.nextInt()); - assertEquals(1.0, reader.nextDouble(), 0); - assertEquals(-1L, reader.nextLong()); - assertEquals(-1, reader.nextInt()); - assertEquals(-1.0, reader.nextDouble(), 0); + assertThat(reader.nextLong()).isEqualTo(0L); + assertThat(reader.nextInt()).isEqualTo(0); + assertThat(reader.nextDouble()).isEqualTo(0.0); + assertThat(reader.nextLong()).isEqualTo(1L); + assertThat(reader.nextInt()).isEqualTo(1); + assertThat(reader.nextDouble()).isEqualTo(1.0); + assertThat(reader.nextLong()).isEqualTo(-1L); + assertThat(reader.nextInt()).isEqualTo(-1); + assertThat(reader.nextDouble()).isEqualTo(-1.0); try { reader.nextInt(); fail(); } catch (NumberFormatException expected) { } - assertEquals(Long.MIN_VALUE, reader.nextLong()); + assertThat(reader.nextLong()).isEqualTo(Long.MIN_VALUE); try { reader.nextInt(); fail(); } catch (NumberFormatException expected) { } - assertEquals(Long.MAX_VALUE, reader.nextLong()); + assertThat(reader.nextLong()).isEqualTo(Long.MAX_VALUE); reader.endArray(); - assertEquals(JsonToken.END_DOCUMENT, reader.peek()); + assertThat(reader.peek()).isEqualTo(JsonToken.END_DOCUMENT); } @Test @@ -558,19 +556,19 @@ public void disabled_testNumberWithOctalPrefix() throws IOException { fail(); } catch (MalformedJsonException expected) { } - assertEquals("01", reader.nextString()); + assertThat(reader.nextString()).isEqualTo("01"); reader.endArray(); - assertEquals(JsonToken.END_DOCUMENT, reader.peek()); + assertThat(reader.peek()).isEqualTo(JsonToken.END_DOCUMENT); } @Test public void testBooleans() throws IOException { JsonReader reader = new JsonReader(reader("[true,false]")); reader.beginArray(); - assertEquals(true, reader.nextBoolean()); - assertEquals(false, reader.nextBoolean()); + assertThat(reader.nextBoolean()).isTrue(); + assertThat(reader.nextBoolean()).isFalse(); reader.endArray(); - assertEquals(JsonToken.END_DOCUMENT, reader.peek()); + assertThat(reader.peek()).isEqualTo(JsonToken.END_DOCUMENT); } @Test @@ -578,13 +576,13 @@ public void testPeekingUnquotedStringsPrefixedWithBooleans() throws IOException JsonReader reader = new JsonReader(reader("[truey]")); reader.setLenient(true); reader.beginArray(); - assertEquals(STRING, reader.peek()); + assertThat(reader.peek()).isEqualTo(STRING); try { reader.nextBoolean(); fail(); } catch (IllegalStateException expected) { } - assertEquals("truey", reader.nextString()); + assertThat(reader.nextString()).isEqualTo("truey"); reader.endArray(); } @@ -636,8 +634,8 @@ public void testMalformedNumbers() throws IOException { private void assertNotANumber(String s) throws IOException { JsonReader reader = new JsonReader(reader(s)); reader.setLenient(true); - assertEquals(JsonToken.STRING, reader.peek()); - assertEquals(s, reader.nextString()); + assertThat(reader.peek()).isEqualTo(JsonToken.STRING); + assertThat(reader.nextString()).isEqualTo(s); JsonReader strictReader = new JsonReader(reader(s)); try { @@ -652,13 +650,13 @@ public void testPeekingUnquotedStringsPrefixedWithIntegers() throws IOException JsonReader reader = new JsonReader(reader("[12.34e5x]")); reader.setLenient(true); reader.beginArray(); - assertEquals(STRING, reader.peek()); + assertThat(reader.peek()).isEqualTo(STRING); try { reader.nextInt(); fail(); } catch (NumberFormatException expected) { } - assertEquals("12.34e5x", reader.nextString()); + assertThat(reader.nextString()).isEqualTo("12.34e5x"); } @Test @@ -666,8 +664,8 @@ public void testPeekLongMinValue() throws IOException { JsonReader reader = new JsonReader(reader("[-9223372036854775808]")); reader.setLenient(true); reader.beginArray(); - assertEquals(NUMBER, reader.peek()); - assertEquals(-9223372036854775808L, reader.nextLong()); + assertThat(reader.peek()).isEqualTo(NUMBER); + assertThat(reader.nextLong()).isEqualTo(-9223372036854775808L); } @Test @@ -675,8 +673,8 @@ public void testPeekLongMaxValue() throws IOException { JsonReader reader = new JsonReader(reader("[9223372036854775807]")); reader.setLenient(true); reader.beginArray(); - assertEquals(NUMBER, reader.peek()); - assertEquals(9223372036854775807L, reader.nextLong()); + assertThat(reader.peek()).isEqualTo(NUMBER); + assertThat(reader.nextLong()).isEqualTo(9223372036854775807L); } @Test @@ -684,7 +682,7 @@ public void testLongLargerThanMaxLongThatWrapsAround() throws IOException { JsonReader reader = new JsonReader(reader("[22233720368547758070]")); reader.setLenient(true); reader.beginArray(); - assertEquals(NUMBER, reader.peek()); + assertThat(reader.peek()).isEqualTo(NUMBER); try { reader.nextLong(); fail(); @@ -697,7 +695,7 @@ public void testLongLargerThanMinLongThatWrapsAround() throws IOException { JsonReader reader = new JsonReader(reader("[-22233720368547758070]")); reader.setLenient(true); reader.beginArray(); - assertEquals(NUMBER, reader.peek()); + assertThat(reader.peek()).isEqualTo(NUMBER); try { reader.nextLong(); fail(); @@ -714,8 +712,8 @@ public void testNegativeZero() throws Exception { JsonReader reader = new JsonReader(reader("[-0]")); reader.setLenient(false); reader.beginArray(); - assertEquals(NUMBER, reader.peek()); - assertEquals("-0", reader.nextString()); + assertThat(reader.peek()).isEqualTo(NUMBER); + assertThat(reader.nextString()).isEqualTo("-0"); } /** @@ -728,7 +726,7 @@ public void disabled_testPeekLargerThanLongMaxValue() throws IOException { JsonReader reader = new JsonReader(reader("[9223372036854775808]")); reader.setLenient(true); reader.beginArray(); - assertEquals(NUMBER, reader.peek()); + assertThat(reader.peek()).isEqualTo(NUMBER); try { reader.nextLong(); fail(); @@ -746,13 +744,13 @@ public void disabled_testPeekLargerThanLongMinValue() throws IOException { JsonReader reader = new JsonReader(reader("[-9223372036854775809]")); reader.setLenient(true); reader.beginArray(); - assertEquals(NUMBER, reader.peek()); + assertThat(reader.peek()).isEqualTo(NUMBER); try { reader.nextLong(); fail(); } catch (NumberFormatException expected) { } - assertEquals(-9223372036854775809d, reader.nextDouble(), 0); + assertThat(reader.nextDouble()).isEqualTo(-9223372036854775809d); } /** @@ -765,7 +763,7 @@ public void disabled_testHighPrecisionLong() throws IOException { String json = "[9223372036854775806.000]"; JsonReader reader = new JsonReader(reader(json)); reader.beginArray(); - assertEquals(9223372036854775806L, reader.nextLong()); + assertThat(reader.nextLong()).isEqualTo(9223372036854775806L); reader.endArray(); } @@ -774,13 +772,13 @@ public void testPeekMuchLargerThanLongMinValue() throws IOException { JsonReader reader = new JsonReader(reader("[-92233720368547758080]")); reader.setLenient(true); reader.beginArray(); - assertEquals(NUMBER, reader.peek()); + assertThat(reader.peek()).isEqualTo(NUMBER); try { reader.nextLong(); fail(); } catch (NumberFormatException expected) { } - assertEquals(-92233720368547758080d, reader.nextDouble(), 0); + assertThat(reader.nextDouble()).isEqualTo(-92233720368547758080d); } @Test @@ -788,29 +786,29 @@ public void testQuotedNumberWithEscape() throws IOException { JsonReader reader = new JsonReader(reader("[\"12\u00334\"]")); reader.setLenient(true); reader.beginArray(); - assertEquals(STRING, reader.peek()); - assertEquals(1234, reader.nextInt()); + assertThat(reader.peek()).isEqualTo(STRING); + assertThat(reader.nextInt()).isEqualTo(1234); } @Test public void testMixedCaseLiterals() throws IOException { JsonReader reader = new JsonReader(reader("[True,TruE,False,FALSE,NULL,nulL]")); reader.beginArray(); - assertEquals(true, reader.nextBoolean()); - assertEquals(true, reader.nextBoolean()); - assertEquals(false, reader.nextBoolean()); - assertEquals(false, reader.nextBoolean()); + assertThat(reader.nextBoolean()).isTrue(); + assertThat(reader.nextBoolean()).isTrue(); + assertThat(reader.nextBoolean()).isFalse(); + assertThat(reader.nextBoolean()).isFalse(); reader.nextNull(); reader.nextNull(); reader.endArray(); - assertEquals(JsonToken.END_DOCUMENT, reader.peek()); + assertThat(reader.peek()).isEqualTo(JsonToken.END_DOCUMENT); } @Test public void testMissingValue() throws IOException { JsonReader reader = new JsonReader(reader("{\"a\":}")); reader.beginObject(); - assertEquals("a", reader.nextName()); + assertThat(reader.nextName()).isEqualTo("a"); try { reader.nextString(); fail(); @@ -822,8 +820,8 @@ public void testMissingValue() throws IOException { public void testPrematureEndOfInput() throws IOException { JsonReader reader = new JsonReader(reader("{\"a\":true,")); reader.beginObject(); - assertEquals("a", reader.nextName()); - assertEquals(true, reader.nextBoolean()); + assertThat(reader.nextName()).isEqualTo("a"); + assertThat(reader.nextBoolean()).isTrue(); try { reader.nextName(); fail(); @@ -871,7 +869,7 @@ public void testNextFailuresDoNotAdvance() throws IOException { fail(); } catch (IllegalStateException expected) { } - assertEquals("a", reader.nextName()); + assertThat(reader.nextName()).isEqualTo("a"); try { reader.nextName(); fail(); @@ -897,7 +895,7 @@ public void testNextFailuresDoNotAdvance() throws IOException { fail(); } catch (IllegalStateException expected) { } - assertEquals(true, reader.nextBoolean()); + assertThat(reader.nextBoolean()).isTrue(); try { reader.nextString(); fail(); @@ -919,7 +917,7 @@ public void testNextFailuresDoNotAdvance() throws IOException { } catch (IllegalStateException expected) { } reader.endObject(); - assertEquals(JsonToken.END_DOCUMENT, reader.peek()); + assertThat(reader.peek()).isEqualTo(JsonToken.END_DOCUMENT); reader.close(); } @@ -932,7 +930,7 @@ public void testIntegerMismatchFailuresDoNotAdvance() throws IOException { fail(); } catch (NumberFormatException expected) { } - assertEquals(1.5d, reader.nextDouble(), 0); + assertThat(reader.nextDouble()).isEqualTo(1.5d); reader.endArray(); } @@ -962,7 +960,7 @@ public void testNullLiteralIsNotAString() throws IOException { public void testStrictNameValueSeparator() throws IOException { JsonReader reader = new JsonReader(reader("{\"a\"=true}")); reader.beginObject(); - assertEquals("a", reader.nextName()); + assertThat(reader.nextName()).isEqualTo("a"); try { reader.nextBoolean(); fail(); @@ -971,7 +969,7 @@ public void testStrictNameValueSeparator() throws IOException { reader = new JsonReader(reader("{\"a\"=>true}")); reader.beginObject(); - assertEquals("a", reader.nextName()); + assertThat(reader.nextName()).isEqualTo("a"); try { reader.nextBoolean(); fail(); @@ -984,21 +982,21 @@ public void testLenientNameValueSeparator() throws IOException { JsonReader reader = new JsonReader(reader("{\"a\"=true}")); reader.setLenient(true); reader.beginObject(); - assertEquals("a", reader.nextName()); - assertEquals(true, reader.nextBoolean()); + assertThat(reader.nextName()).isEqualTo("a"); + assertThat(reader.nextBoolean()).isTrue(); reader = new JsonReader(reader("{\"a\"=>true}")); reader.setLenient(true); reader.beginObject(); - assertEquals("a", reader.nextName()); - assertEquals(true, reader.nextBoolean()); + assertThat(reader.nextName()).isEqualTo("a"); + assertThat(reader.nextBoolean()).isTrue(); } @Test public void testStrictNameValueSeparatorWithSkipValue() throws IOException { JsonReader reader = new JsonReader(reader("{\"a\"=true}")); reader.beginObject(); - assertEquals("a", reader.nextName()); + assertThat(reader.nextName()).isEqualTo("a"); try { reader.skipValue(); fail(); @@ -1007,7 +1005,7 @@ public void testStrictNameValueSeparatorWithSkipValue() throws IOException { reader = new JsonReader(reader("{\"a\"=>true}")); reader.beginObject(); - assertEquals("a", reader.nextName()); + assertThat(reader.nextName()).isEqualTo("a"); try { reader.skipValue(); fail(); @@ -1019,19 +1017,19 @@ public void testStrictNameValueSeparatorWithSkipValue() throws IOException { public void testCommentsInStringValue() throws Exception { JsonReader reader = new JsonReader(reader("[\"// comment\"]")); reader.beginArray(); - assertEquals("// comment", reader.nextString()); + assertThat(reader.nextString()).isEqualTo("// comment"); reader.endArray(); reader = new JsonReader(reader("{\"a\":\"#someComment\"}")); reader.beginObject(); - assertEquals("a", reader.nextName()); - assertEquals("#someComment", reader.nextString()); + assertThat(reader.nextName()).isEqualTo("a"); + assertThat(reader.nextString()).isEqualTo("#someComment"); reader.endObject(); reader = new JsonReader(reader("{\"#//a\":\"#some //Comment\"}")); reader.beginObject(); - assertEquals("#//a", reader.nextName()); - assertEquals("#some //Comment", reader.nextString()); + assertThat(reader.nextName()).isEqualTo("#//a"); + assertThat(reader.nextString()).isEqualTo("#some //Comment"); reader.endObject(); } @@ -1067,17 +1065,17 @@ public void testLenientComments() throws IOException { JsonReader reader = new JsonReader(reader("[// comment \n true]")); reader.setLenient(true); reader.beginArray(); - assertEquals(true, reader.nextBoolean()); + assertThat(reader.nextBoolean()).isTrue(); reader = new JsonReader(reader("[# comment \n true]")); reader.setLenient(true); reader.beginArray(); - assertEquals(true, reader.nextBoolean()); + assertThat(reader.nextBoolean()).isTrue(); reader = new JsonReader(reader("[/* comment */ true]")); reader.setLenient(true); reader.beginArray(); - assertEquals(true, reader.nextBoolean()); + assertThat(reader.nextBoolean()).isTrue(); } @Test @@ -1123,7 +1121,7 @@ public void testLenientUnquotedNames() throws IOException { JsonReader reader = new JsonReader(reader("{a:true}")); reader.setLenient(true); reader.beginObject(); - assertEquals("a", reader.nextName()); + assertThat(reader.nextName()).isEqualTo("a"); } @Test @@ -1153,7 +1151,7 @@ public void testLenientSingleQuotedNames() throws IOException { JsonReader reader = new JsonReader(reader("{'a':true}")); reader.setLenient(true); reader.beginObject(); - assertEquals("a", reader.nextName()); + assertThat(reader.nextName()).isEqualTo("a"); } @Test @@ -1194,7 +1192,7 @@ public void testLenientUnquotedStrings() throws IOException { JsonReader reader = new JsonReader(reader("[a]")); reader.setLenient(true); reader.beginArray(); - assertEquals("a", reader.nextString()); + assertThat(reader.nextString()).isEqualTo("a"); } @Test @@ -1213,7 +1211,7 @@ public void testLenientSingleQuotedStrings() throws IOException { JsonReader reader = new JsonReader(reader("['a']")); reader.setLenient(true); reader.beginArray(); - assertEquals("a", reader.nextString()); + assertThat(reader.nextString()).isEqualTo("a"); } @Test @@ -1244,8 +1242,8 @@ public void testLenientSemicolonDelimitedArray() throws IOException { JsonReader reader = new JsonReader(reader("[true;true]")); reader.setLenient(true); reader.beginArray(); - assertEquals(true, reader.nextBoolean()); - assertEquals(true, reader.nextBoolean()); + assertThat(reader.nextBoolean()).isTrue(); + assertThat(reader.nextBoolean()).isTrue(); } @Test @@ -1264,7 +1262,7 @@ public void testStrictSemicolonDelimitedArrayWithSkipValue() throws IOException public void testStrictSemicolonDelimitedNameValuePair() throws IOException { JsonReader reader = new JsonReader(reader("{\"a\":true;\"b\":true}")); reader.beginObject(); - assertEquals("a", reader.nextName()); + assertThat(reader.nextName()).isEqualTo("a"); try { reader.nextBoolean(); reader.nextName(); @@ -1278,16 +1276,16 @@ public void testLenientSemicolonDelimitedNameValuePair() throws IOException { JsonReader reader = new JsonReader(reader("{\"a\":true;\"b\":true}")); reader.setLenient(true); reader.beginObject(); - assertEquals("a", reader.nextName()); - assertEquals(true, reader.nextBoolean()); - assertEquals("b", reader.nextName()); + assertThat(reader.nextName()).isEqualTo("a"); + assertThat(reader.nextBoolean()).isTrue(); + assertThat(reader.nextName()).isEqualTo("b"); } @Test public void testStrictSemicolonDelimitedNameValuePairWithSkipValue() throws IOException { JsonReader reader = new JsonReader(reader("{\"a\":true;\"b\":true}")); reader.beginObject(); - assertEquals("a", reader.nextName()); + assertThat(reader.nextName()).isEqualTo("a"); try { reader.skipValue(); reader.skipValue(); @@ -1300,7 +1298,7 @@ public void testStrictSemicolonDelimitedNameValuePairWithSkipValue() throws IOEx public void testStrictUnnecessaryArraySeparators() throws IOException { JsonReader reader = new JsonReader(reader("[true,,true]")); reader.beginArray(); - assertEquals(true, reader.nextBoolean()); + assertThat(reader.nextBoolean()).isTrue(); try { reader.nextNull(); fail(); @@ -1317,7 +1315,7 @@ public void testStrictUnnecessaryArraySeparators() throws IOException { reader = new JsonReader(reader("[true,]")); reader.beginArray(); - assertEquals(true, reader.nextBoolean()); + assertThat(reader.nextBoolean()).isTrue(); try { reader.nextNull(); fail(); @@ -1338,22 +1336,22 @@ public void testLenientUnnecessaryArraySeparators() throws IOException { JsonReader reader = new JsonReader(reader("[true,,true]")); reader.setLenient(true); reader.beginArray(); - assertEquals(true, reader.nextBoolean()); + assertThat(reader.nextBoolean()).isTrue(); reader.nextNull(); - assertEquals(true, reader.nextBoolean()); + assertThat(reader.nextBoolean()).isTrue(); reader.endArray(); reader = new JsonReader(reader("[,true]")); reader.setLenient(true); reader.beginArray(); reader.nextNull(); - assertEquals(true, reader.nextBoolean()); + assertThat(reader.nextBoolean()).isTrue(); reader.endArray(); reader = new JsonReader(reader("[true,]")); reader.setLenient(true); reader.beginArray(); - assertEquals(true, reader.nextBoolean()); + assertThat(reader.nextBoolean()).isTrue(); reader.nextNull(); reader.endArray(); @@ -1369,7 +1367,7 @@ public void testLenientUnnecessaryArraySeparators() throws IOException { public void testStrictUnnecessaryArraySeparatorsWithSkipValue() throws IOException { JsonReader reader = new JsonReader(reader("[true,,true]")); reader.beginArray(); - assertEquals(true, reader.nextBoolean()); + assertThat(reader.nextBoolean()).isTrue(); try { reader.skipValue(); fail(); @@ -1386,7 +1384,7 @@ public void testStrictUnnecessaryArraySeparatorsWithSkipValue() throws IOExcepti reader = new JsonReader(reader("[true,]")); reader.beginArray(); - assertEquals(true, reader.nextBoolean()); + assertThat(reader.nextBoolean()).isTrue(); try { reader.skipValue(); fail(); @@ -1420,10 +1418,10 @@ public void testLenientMultipleTopLevelValues() throws IOException { reader.setLenient(true); reader.beginArray(); reader.endArray(); - assertEquals(true, reader.nextBoolean()); + assertThat(reader.nextBoolean()).isTrue(); reader.beginObject(); reader.endObject(); - assertEquals(JsonToken.END_DOCUMENT, reader.peek()); + assertThat(reader.peek()).isEqualTo(JsonToken.END_DOCUMENT); } @Test @@ -1441,36 +1439,36 @@ public void testStrictMultipleTopLevelValuesWithSkipValue() throws IOException { @Test public void testTopLevelValueTypes() throws IOException { JsonReader reader1 = new JsonReader(reader("true")); - assertTrue(reader1.nextBoolean()); - assertEquals(JsonToken.END_DOCUMENT, reader1.peek()); + assertThat(reader1.nextBoolean()).isTrue(); + assertThat(reader1.peek()).isEqualTo(JsonToken.END_DOCUMENT); JsonReader reader2 = new JsonReader(reader("false")); - assertFalse(reader2.nextBoolean()); - assertEquals(JsonToken.END_DOCUMENT, reader2.peek()); + assertThat(reader2.nextBoolean()).isFalse(); + assertThat(reader2.peek()).isEqualTo(JsonToken.END_DOCUMENT); JsonReader reader3 = new JsonReader(reader("null")); - assertEquals(JsonToken.NULL, reader3.peek()); + assertThat(reader3.peek()).isEqualTo(JsonToken.NULL); reader3.nextNull(); - assertEquals(JsonToken.END_DOCUMENT, reader3.peek()); + assertThat(reader3.peek()).isEqualTo(JsonToken.END_DOCUMENT); JsonReader reader4 = new JsonReader(reader("123")); - assertEquals(123, reader4.nextInt()); - assertEquals(JsonToken.END_DOCUMENT, reader4.peek()); + assertThat(reader4.nextInt()).isEqualTo(123); + assertThat(reader4.peek()).isEqualTo(JsonToken.END_DOCUMENT); JsonReader reader5 = new JsonReader(reader("123.4")); - assertEquals(123.4, reader5.nextDouble(), 0); - assertEquals(JsonToken.END_DOCUMENT, reader5.peek()); + assertThat(reader5.nextDouble()).isEqualTo(123.4); + assertThat(reader5.peek()).isEqualTo(JsonToken.END_DOCUMENT); JsonReader reader6 = new JsonReader(reader("\"a\"")); - assertEquals("a", reader6.nextString()); - assertEquals(JsonToken.END_DOCUMENT, reader6.peek()); + assertThat(reader6.nextString()).isEqualTo("a"); + assertThat(reader6.peek()).isEqualTo(JsonToken.END_DOCUMENT); } @Test public void testTopLevelValueTypeWithSkipValue() throws IOException { JsonReader reader = new JsonReader(reader("true")); reader.skipValue(); - assertEquals(JsonToken.END_DOCUMENT, reader.peek()); + assertThat(reader.peek()).isEqualTo(JsonToken.END_DOCUMENT); } @Test @@ -1499,7 +1497,7 @@ public void testLenientNonExecutePrefix() throws IOException { reader.setLenient(true); reader.beginArray(); reader.endArray(); - assertEquals(JsonToken.END_DOCUMENT, reader.peek()); + assertThat(reader.peek()).isEqualTo(JsonToken.END_DOCUMENT); } @Test @@ -1508,7 +1506,7 @@ public void testLenientNonExecutePrefixWithLeadingWhitespace() throws IOExceptio reader.setLenient(true); reader.beginArray(); reader.endArray(); - assertEquals(JsonToken.END_DOCUMENT, reader.peek()); + assertThat(reader.peek()).isEqualTo(JsonToken.END_DOCUMENT); } @Test @@ -1516,7 +1514,7 @@ public void testLenientPartialNonExecutePrefix() { JsonReader reader = new JsonReader(reader(")]}' []")); reader.setLenient(true); try { - assertEquals(")", reader.nextString()); + assertThat(reader.nextString()).isEqualTo(")"); reader.nextString(); fail(); } catch (IOException expected) { @@ -1604,7 +1602,7 @@ private void testFailWithPosition(String message, String json) throws IOExceptio reader1.peek(); fail(); } catch (IOException expected) { - assertEquals(message, expected.getMessage()); + assertThat(expected.getMessage()).isEqualTo(message); } // Also validate that it works when skipping. @@ -1616,7 +1614,7 @@ private void testFailWithPosition(String message, String json) throws IOExceptio reader2.peek(); fail(); } catch (IOException expected) { - assertEquals(message, expected.getMessage()); + assertThat(expected.getMessage()).isEqualTo(message); } } @@ -1634,7 +1632,7 @@ public void testFailWithPositionDeepPath() throws IOException { reader.peek(); fail(); } catch (IOException expected) { - assertEquals("Expected value at line 1 column 14 path $[1].a[2]", expected.getMessage()); + assertThat(expected.getMessage()).isEqualTo("Expected value at line 1 column 14 path $[1].a[2]"); } } @@ -1643,7 +1641,7 @@ public void testStrictVeryLongNumber() throws IOException { JsonReader reader = new JsonReader(reader("[0." + repeat('9', 8192) + "]")); reader.beginArray(); try { - assertEquals(1d, reader.nextDouble(), 0); + assertThat(reader.nextDouble()).isEqualTo(1d); fail(); } catch (MalformedJsonException expected) { } @@ -1654,10 +1652,10 @@ public void testLenientVeryLongNumber() throws IOException { JsonReader reader = new JsonReader(reader("[0." + repeat('9', 8192) + "]")); reader.setLenient(true); reader.beginArray(); - assertEquals(JsonToken.STRING, reader.peek()); - assertEquals(1d, reader.nextDouble(), 0); + assertThat(reader.peek()).isEqualTo(JsonToken.STRING); + assertThat(reader.nextDouble()).isEqualTo(1d); reader.endArray(); - assertEquals(JsonToken.END_DOCUMENT, reader.peek()); + assertThat(reader.peek()).isEqualTo(JsonToken.END_DOCUMENT); } @Test @@ -1666,7 +1664,7 @@ public void testVeryLongUnquotedLiteral() throws IOException { JsonReader reader = new JsonReader(reader("[" + literal + "]")); reader.setLenient(true); reader.beginArray(); - assertEquals(literal, reader.nextString()); + assertThat(reader.nextString()).isEqualTo(literal); reader.endArray(); } @@ -1678,12 +1676,12 @@ public void testDeeplyNestedArrays() throws IOException { for (int i = 0; i < 40; i++) { reader.beginArray(); } - assertEquals("$[0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0]" - + "[0][0][0][0][0][0][0][0][0][0][0][0][0][0]", reader.getPath()); + assertThat(reader.getPath()).isEqualTo("$[0][0][0][0][0][0][0][0][0][0][0][0][0][0][0]" + + "[0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0]"); for (int i = 0; i < 40; i++) { reader.endArray(); } - assertEquals(JsonToken.END_DOCUMENT, reader.peek()); + assertThat(reader.peek()).isEqualTo(JsonToken.END_DOCUMENT); } @Test @@ -1698,15 +1696,14 @@ public void testDeeplyNestedObjects() throws IOException { JsonReader reader = new JsonReader(reader(json)); for (int i = 0; i < 40; i++) { reader.beginObject(); - assertEquals("a", reader.nextName()); + assertThat(reader.nextName()).isEqualTo("a"); } - assertEquals("$.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a" - + ".a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a", reader.getPath()); - assertEquals(true, reader.nextBoolean()); + assertThat(reader.getPath()); + assertThat(reader.nextBoolean()).isTrue(); for (int i = 0; i < 40; i++) { reader.endObject(); } - assertEquals(JsonToken.END_DOCUMENT, reader.peek()); + assertThat(reader.peek()).isEqualTo(JsonToken.END_DOCUMENT); } // http://code.google.com/p/google-gson/issues/detail?id=409 @@ -1748,8 +1745,8 @@ public void testUnterminatedObject() throws IOException { JsonReader reader = new JsonReader(reader("{\"a\":\"android\"x")); reader.setLenient(true); reader.beginObject(); - assertEquals("a", reader.nextName()); - assertEquals("android", reader.nextString()); + assertThat(reader.nextName()).isEqualTo("a"); + assertThat(reader.nextString()).isEqualTo("android"); try { reader.peek(); fail(); @@ -1765,7 +1762,7 @@ public void testVeryLongQuotedString() throws IOException { String json = "[\"" + string + "\"]"; JsonReader reader = new JsonReader(reader(json)); reader.beginArray(); - assertEquals(string, reader.nextString()); + assertThat(reader.nextString()).isEqualTo(string); reader.endArray(); } @@ -1778,7 +1775,7 @@ public void testVeryLongUnquotedString() throws IOException { JsonReader reader = new JsonReader(reader(json)); reader.setLenient(true); reader.beginArray(); - assertEquals(string, reader.nextString()); + assertThat(reader.nextString()).isEqualTo(string); reader.endArray(); } @@ -1791,7 +1788,7 @@ public void testVeryLongUnterminatedString() throws IOException { JsonReader reader = new JsonReader(reader(json)); reader.setLenient(true); reader.beginArray(); - assertEquals(string, reader.nextString()); + assertThat(reader.nextString()).isEqualTo(string); try { reader.peek(); fail(); @@ -1813,7 +1810,7 @@ public void testSkipTopLevelUnquotedString() throws IOException { JsonReader reader = new JsonReader(reader(repeat('x', 8192))); reader.setLenient(true); reader.skipValue(); - assertEquals(JsonToken.END_DOCUMENT, reader.peek()); + assertThat(reader.peek()).isEqualTo(JsonToken.END_DOCUMENT); } @Test @@ -1829,7 +1826,7 @@ public void testSkipTopLevelQuotedString() throws IOException { JsonReader reader = new JsonReader(reader("\"" + repeat('x', 8192) + "\"")); reader.setLenient(true); reader.skipValue(); - assertEquals(JsonToken.END_DOCUMENT, reader.peek()); + assertThat(reader.peek()).isEqualTo(JsonToken.END_DOCUMENT); } @Test @@ -1837,7 +1834,7 @@ public void testStringAsNumberWithTruncatedExponent() throws IOException { JsonReader reader = new JsonReader(reader("[123e]")); reader.setLenient(true); reader.beginArray(); - assertEquals(STRING, reader.peek()); + assertThat(reader.peek()).isEqualTo(STRING); } @Test @@ -1845,7 +1842,7 @@ public void testStringAsNumberWithDigitAndNonDigitExponent() throws IOException JsonReader reader = new JsonReader(reader("[123e4b]")); reader.setLenient(true); reader.beginArray(); - assertEquals(STRING, reader.peek()); + assertThat(reader.peek()).isEqualTo(STRING); } @Test @@ -1853,30 +1850,30 @@ public void testStringAsNumberWithNonDigitExponent() throws IOException { JsonReader reader = new JsonReader(reader("[123eb]")); reader.setLenient(true); reader.beginArray(); - assertEquals(STRING, reader.peek()); + assertThat(reader.peek()).isEqualTo(STRING); } @Test public void testEmptyStringName() throws IOException { JsonReader reader = new JsonReader(reader("{\"\":true}")); reader.setLenient(true); - assertEquals(BEGIN_OBJECT, reader.peek()); + assertThat(reader.peek()).isEqualTo(BEGIN_OBJECT); reader.beginObject(); - assertEquals(NAME, reader.peek()); - assertEquals("", reader.nextName()); - assertEquals(JsonToken.BOOLEAN, reader.peek()); - assertEquals(true, reader.nextBoolean()); - assertEquals(JsonToken.END_OBJECT, reader.peek()); + assertThat(reader.peek()).isEqualTo(NAME); + assertThat(reader.nextName()).isEqualTo(""); + assertThat(reader.peek()).isEqualTo(JsonToken.BOOLEAN); + assertThat(reader.nextBoolean()).isTrue(); + assertThat(reader.peek()).isEqualTo(JsonToken.END_OBJECT); reader.endObject(); - assertEquals(JsonToken.END_DOCUMENT, reader.peek()); + assertThat(reader.peek()).isEqualTo(JsonToken.END_DOCUMENT); } @Test public void testStrictExtraCommasInMaps() throws IOException { JsonReader reader = new JsonReader(reader("{\"a\":\"b\",}")); reader.beginObject(); - assertEquals("a", reader.nextName()); - assertEquals("b", reader.nextString()); + assertThat(reader.nextName()).isEqualTo("a"); + assertThat(reader.nextString()).isEqualTo("b"); try { reader.peek(); fail(); @@ -1889,8 +1886,8 @@ public void testLenientExtraCommasInMaps() throws IOException { JsonReader reader = new JsonReader(reader("{\"a\":\"b\",}")); reader.setLenient(true); reader.beginObject(); - assertEquals("a", reader.nextName()); - assertEquals("b", reader.nextString()); + assertThat(reader.nextName()).isEqualTo("a"); + assertThat(reader.nextString()).isEqualTo("b"); try { reader.peek(); fail(); @@ -1956,7 +1953,7 @@ public void testUnterminatedStringFailure() throws IOException { JsonReader reader = new JsonReader(reader("[\"string")); reader.setLenient(true); reader.beginArray(); - assertEquals(JsonToken.STRING, reader.peek()); + assertThat(reader.peek()).isEqualTo(JsonToken.STRING); try { reader.nextString(); fail(); @@ -1977,7 +1974,7 @@ public void testReadAcrossBuffers() throws IOException { JsonReader reader = new JsonReader(reader(sb.toString())); reader.setLenient(true); JsonToken token = reader.peek(); - assertEquals(JsonToken.NUMBER, token); + assertThat(token).isEqualTo(JsonToken.NUMBER); } private void assertDocument(String document, Object... expectations) throws IOException { @@ -1993,13 +1990,13 @@ private void assertDocument(String document, Object... expectations) throws IOEx } else if (expectation == END_ARRAY) { reader.endArray(); } else if (expectation == NAME) { - assertEquals("name", reader.nextName()); + assertThat(reader.nextName()).isEqualTo("name"); } else if (expectation == BOOLEAN) { - assertEquals(false, reader.nextBoolean()); + assertThat(reader.nextBoolean()).isFalse(); } else if (expectation == STRING) { - assertEquals("string", reader.nextString()); + assertThat(reader.nextString()).isEqualTo("string"); } else if (expectation == NUMBER) { - assertEquals(123, reader.nextInt()); + assertThat(reader.nextInt()).isEqualTo(123); } else if (expectation == NULL) { reader.nextNull(); } else if (expectation == IOException.class) { diff --git a/gson/src/test/java/com/google/gson/stream/JsonWriterTest.java b/gson/src/test/java/com/google/gson/stream/JsonWriterTest.java index 20c4558c6c..a0896676c5 100644 --- a/gson/src/test/java/com/google/gson/stream/JsonWriterTest.java +++ b/gson/src/test/java/com/google/gson/stream/JsonWriterTest.java @@ -16,7 +16,7 @@ package com.google.gson.stream; -import static org.junit.Assert.assertEquals; +import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.fail; import com.google.gson.internal.LazilyParsedNumber; @@ -35,31 +35,31 @@ public void testTopLevelValueTypes() throws IOException { JsonWriter writer1 = new JsonWriter(string1); writer1.value(true); writer1.close(); - assertEquals("true", string1.toString()); + assertThat(string1.toString()).isEqualTo("true"); StringWriter string2 = new StringWriter(); JsonWriter writer2 = new JsonWriter(string2); writer2.nullValue(); writer2.close(); - assertEquals("null", string2.toString()); + assertThat(string2.toString()).isEqualTo("null"); StringWriter string3 = new StringWriter(); JsonWriter writer3 = new JsonWriter(string3); writer3.value(123); writer3.close(); - assertEquals("123", string3.toString()); + assertThat(string3.toString()).isEqualTo("123"); StringWriter string4 = new StringWriter(); JsonWriter writer4 = new JsonWriter(string4); writer4.value(123.4); writer4.close(); - assertEquals("123.4", string4.toString()); + assertThat(string4.toString()).isEqualTo("123.4"); StringWriter string5 = new StringWriter(); JsonWriter writert = new JsonWriter(string5); writert.value("a"); writert.close(); - assertEquals("\"a\"", string5.toString()); + assertThat(string5.toString()).isEqualTo("\"a\""); } @Test @@ -170,7 +170,7 @@ public void testNullStringValue() throws IOException { jsonWriter.name("a"); jsonWriter.value((String) null); jsonWriter.endObject(); - assertEquals("{\"a\":null}", stringWriter.toString()); + assertThat(stringWriter.toString()).isEqualTo("{\"a\":null}"); } @Test @@ -183,7 +183,7 @@ public void testJsonValue() throws IOException { jsonWriter.name("c"); jsonWriter.value(1); jsonWriter.endObject(); - assertEquals("{\"a\":{\"b\":true},\"c\":1}", stringWriter.toString()); + assertThat(stringWriter.toString()).isEqualTo("{\"a\":{\"b\":true},\"c\":1}"); } @Test @@ -195,19 +195,19 @@ public void testNonFiniteFloats() throws IOException { jsonWriter.value(Float.NaN); fail(); } catch (IllegalArgumentException expected) { - assertEquals("Numeric values must be finite, but was NaN", expected.getMessage()); + assertThat(expected).hasMessageThat().isEqualTo("Numeric values must be finite, but was NaN"); } try { jsonWriter.value(Float.NEGATIVE_INFINITY); fail(); } catch (IllegalArgumentException expected) { - assertEquals("Numeric values must be finite, but was -Infinity", expected.getMessage()); + assertThat(expected).hasMessageThat().isEqualTo("Numeric values must be finite, but was -Infinity"); } try { jsonWriter.value(Float.POSITIVE_INFINITY); fail(); } catch (IllegalArgumentException expected) { - assertEquals("Numeric values must be finite, but was Infinity", expected.getMessage()); + assertThat(expected).hasMessageThat().isEqualTo("Numeric values must be finite, but was Infinity"); } } @@ -220,19 +220,19 @@ public void testNonFiniteDoubles() throws IOException { jsonWriter.value(Double.NaN); fail(); } catch (IllegalArgumentException expected) { - assertEquals("Numeric values must be finite, but was NaN", expected.getMessage()); + assertThat(expected).hasMessageThat().isEqualTo("Numeric values must be finite, but was NaN"); } try { jsonWriter.value(Double.NEGATIVE_INFINITY); fail(); } catch (IllegalArgumentException expected) { - assertEquals("Numeric values must be finite, but was -Infinity", expected.getMessage()); + assertThat(expected).hasMessageThat().isEqualTo("Numeric values must be finite, but was -Infinity"); } try { jsonWriter.value(Double.POSITIVE_INFINITY); fail(); } catch (IllegalArgumentException expected) { - assertEquals("Numeric values must be finite, but was Infinity", expected.getMessage()); + assertThat(expected).hasMessageThat().isEqualTo("Numeric values must be finite, but was Infinity"); } } @@ -245,25 +245,25 @@ public void testNonFiniteNumbers() throws IOException { jsonWriter.value(Double.valueOf(Double.NaN)); fail(); } catch (IllegalArgumentException expected) { - assertEquals("Numeric values must be finite, but was NaN", expected.getMessage()); + assertThat(expected).hasMessageThat().isEqualTo("Numeric values must be finite, but was NaN"); } try { jsonWriter.value(Double.valueOf(Double.NEGATIVE_INFINITY)); fail(); } catch (IllegalArgumentException expected) { - assertEquals("Numeric values must be finite, but was -Infinity", expected.getMessage()); + assertThat(expected).hasMessageThat().isEqualTo("Numeric values must be finite, but was -Infinity"); } try { jsonWriter.value(Double.valueOf(Double.POSITIVE_INFINITY)); fail(); } catch (IllegalArgumentException expected) { - assertEquals("Numeric values must be finite, but was Infinity", expected.getMessage()); + assertThat(expected).hasMessageThat().isEqualTo("Numeric values must be finite, but was Infinity"); } try { jsonWriter.value(new LazilyParsedNumber("Infinity")); fail(); } catch (IllegalArgumentException expected) { - assertEquals("Numeric values must be finite, but was Infinity", expected.getMessage()); + assertThat(expected).hasMessageThat().isEqualTo("Numeric values must be finite, but was Infinity"); } } @@ -277,7 +277,7 @@ public void testNonFiniteFloatsWhenLenient() throws IOException { jsonWriter.value(Float.NEGATIVE_INFINITY); jsonWriter.value(Float.POSITIVE_INFINITY); jsonWriter.endArray(); - assertEquals("[NaN,-Infinity,Infinity]", stringWriter.toString()); + assertThat(stringWriter.toString()).isEqualTo("[NaN,-Infinity,Infinity]"); } @Test @@ -290,7 +290,7 @@ public void testNonFiniteDoublesWhenLenient() throws IOException { jsonWriter.value(Double.NEGATIVE_INFINITY); jsonWriter.value(Double.POSITIVE_INFINITY); jsonWriter.endArray(); - assertEquals("[NaN,-Infinity,Infinity]", stringWriter.toString()); + assertThat(stringWriter.toString()).isEqualTo("[NaN,-Infinity,Infinity]"); } @Test @@ -304,7 +304,7 @@ public void testNonFiniteNumbersWhenLenient() throws IOException { jsonWriter.value(Double.valueOf(Double.POSITIVE_INFINITY)); jsonWriter.value(new LazilyParsedNumber("Infinity")); jsonWriter.endArray(); - assertEquals("[NaN,-Infinity,Infinity,Infinity]", stringWriter.toString()); + assertThat(stringWriter.toString()).isEqualTo("[NaN,-Infinity,Infinity,Infinity]"); } @Test @@ -324,18 +324,16 @@ public void testFloats() throws IOException { jsonWriter.value((float) Math.E); jsonWriter.endArray(); jsonWriter.close(); - assertEquals( - "[-0.0," - + "1.0," - + "3.4028235E38," - + "1.4E-45," - + "0.0," - + "-0.5," - + "2.2250739E-38," - + "3.723379," - + "3.1415927," - + "2.7182817]", - stringWriter.toString()); + assertThat(stringWriter.toString()).isEqualTo("[-0.0," + + "1.0," + + "3.4028235E38," + + "1.4E-45," + + "0.0," + + "-0.5," + + "2.2250739E-38," + + "3.723379," + + "3.1415927," + + "2.7182817]"); } @Test @@ -354,7 +352,7 @@ public void testDoubles() throws IOException { jsonWriter.value(Math.E); jsonWriter.endArray(); jsonWriter.close(); - assertEquals("[-0.0," + assertThat(stringWriter.toString()).isEqualTo("[-0.0," + "1.0," + "1.7976931348623157E308," + "4.9E-324," @@ -362,7 +360,7 @@ public void testDoubles() throws IOException { + "-0.5," + "2.2250738585072014E-308," + "3.141592653589793," - + "2.718281828459045]", stringWriter.toString()); + + "2.718281828459045]"); } @Test @@ -377,11 +375,11 @@ public void testLongs() throws IOException { jsonWriter.value(Long.MAX_VALUE); jsonWriter.endArray(); jsonWriter.close(); - assertEquals("[0," + assertThat(stringWriter.toString()).isEqualTo("[0," + "1," + "-1," + "-9223372036854775808," - + "9223372036854775807]", stringWriter.toString()); + + "9223372036854775807]"); } @Test @@ -395,10 +393,10 @@ public void testNumbers() throws IOException { jsonWriter.value(new BigDecimal("3.141592653589793238462643383")); jsonWriter.endArray(); jsonWriter.close(); - assertEquals("[0," + assertThat(stringWriter.toString()).isEqualTo("[0," + "9223372036854775808," + "-9223372036854775809," - + "3.141592653589793238462643383]", stringWriter.toString()); + + "3.141592653589793238462643383]"); } /** @@ -434,7 +432,7 @@ public void testNumbersCustomClass() throws IOException { jsonWriter.value(new LazilyParsedNumber(validNumber)); jsonWriter.close(); - assertEquals(validNumber, stringWriter.toString()); + assertThat(stringWriter.toString()).isEqualTo(validNumber); } } @@ -473,7 +471,7 @@ public void testMalformedNumbers() throws IOException { jsonWriter.value(new LazilyParsedNumber(malformedNumber)); fail("Should have failed writing malformed number: " + malformedNumber); } catch (IllegalArgumentException e) { - assertEquals("String created by class com.google.gson.internal.LazilyParsedNumber is not a valid JSON number: " + malformedNumber, e.getMessage()); + assertThat(e.getMessage()).isEqualTo("String created by class com.google.gson.internal.LazilyParsedNumber is not a valid JSON number: " + malformedNumber); } } } @@ -486,7 +484,7 @@ public void testBooleans() throws IOException { jsonWriter.value(true); jsonWriter.value(false); jsonWriter.endArray(); - assertEquals("[true,false]", stringWriter.toString()); + assertThat(stringWriter.toString()).isEqualTo("[true,false]"); } @Test @@ -498,7 +496,7 @@ public void testBoxedBooleans() throws IOException { jsonWriter.value((Boolean) false); jsonWriter.value((Boolean) null); jsonWriter.endArray(); - assertEquals("[true,false,null]", stringWriter.toString()); + assertThat(stringWriter.toString()).isEqualTo("[true,false,null]"); } @Test @@ -508,7 +506,7 @@ public void testNulls() throws IOException { jsonWriter.beginArray(); jsonWriter.nullValue(); jsonWriter.endArray(); - assertEquals("[null]", stringWriter.toString()); + assertThat(stringWriter.toString()).isEqualTo("[null]"); } @Test @@ -535,7 +533,7 @@ public void testStrings() throws IOException { jsonWriter.value("\0"); jsonWriter.value("\u0019"); jsonWriter.endArray(); - assertEquals("[\"a\"," + assertThat(stringWriter.toString()).isEqualTo("[\"a\"," + "\"a\\\"\"," + "\"\\\"\"," + "\":\"," @@ -552,7 +550,7 @@ public void testStrings() throws IOException { + "\"[\"," + "\"]\"," + "\"\\u0000\"," - + "\"\\u0019\"]", stringWriter.toString()); + + "\"\\u0019\"]"); } @Test @@ -562,7 +560,7 @@ public void testUnicodeLineBreaksEscaped() throws IOException { jsonWriter.beginArray(); jsonWriter.value("\u2028 \u2029"); jsonWriter.endArray(); - assertEquals("[\"\\u2028 \\u2029\"]", stringWriter.toString()); + assertThat(stringWriter.toString()).isEqualTo("[\"\\u2028 \\u2029\"]"); } @Test @@ -571,7 +569,7 @@ public void testEmptyArray() throws IOException { JsonWriter jsonWriter = new JsonWriter(stringWriter); jsonWriter.beginArray(); jsonWriter.endArray(); - assertEquals("[]", stringWriter.toString()); + assertThat(stringWriter.toString()).isEqualTo("[]"); } @Test @@ -580,7 +578,7 @@ public void testEmptyObject() throws IOException { JsonWriter jsonWriter = new JsonWriter(stringWriter); jsonWriter.beginObject(); jsonWriter.endObject(); - assertEquals("{}", stringWriter.toString()); + assertThat(stringWriter.toString()).isEqualTo("{}"); } @Test @@ -597,8 +595,8 @@ public void testObjectsInArrays() throws IOException { jsonWriter.name("d").value(true); jsonWriter.endObject(); jsonWriter.endArray(); - assertEquals("[{\"a\":5,\"b\":false}," - + "{\"c\":6,\"d\":true}]", stringWriter.toString()); + assertThat(stringWriter.toString()).isEqualTo("[{\"a\":5,\"b\":false}," + + "{\"c\":6,\"d\":true}]"); } @Test @@ -617,8 +615,8 @@ public void testArraysInObjects() throws IOException { jsonWriter.value(true); jsonWriter.endArray(); jsonWriter.endObject(); - assertEquals("{\"a\":[5,false]," - + "\"b\":[6,true]}", stringWriter.toString()); + assertThat(stringWriter.toString()).isEqualTo("{\"a\":[5,false]," + + "\"b\":[6,true]}"); } @Test @@ -631,7 +629,7 @@ public void testDeepNestingArrays() throws IOException { for (int i = 0; i < 20; i++) { jsonWriter.endArray(); } - assertEquals("[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]", stringWriter.toString()); + assertThat(stringWriter.toString()).isEqualTo("[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]"); } @Test @@ -647,9 +645,9 @@ public void testDeepNestingObjects() throws IOException { jsonWriter.endObject(); } jsonWriter.endObject(); - assertEquals("{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":" + assertThat(stringWriter.toString()).isEqualTo("{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":" + "{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":{" - + "}}}}}}}}}}}}}}}}}}}}}", stringWriter.toString()); + + "}}}}}}}}}}}}}}}}}}}}}"); } @Test @@ -661,7 +659,7 @@ public void testRepeatedName() throws IOException { jsonWriter.name("a").value(false); jsonWriter.endObject(); // JsonWriter doesn't attempt to detect duplicate names - assertEquals("{\"a\":true,\"a\":false}", stringWriter.toString()); + assertThat(stringWriter.toString()).isEqualTo("{\"a\":true,\"a\":false}"); } @Test @@ -699,7 +697,7 @@ public void testPrettyPrintObject() throws IOException { + " \"i\": 9.0\n" + " }\n" + "}"; - assertEquals(expected, stringWriter.toString()); + assertThat(stringWriter.toString()).isEqualTo(expected); } @Test @@ -737,7 +735,7 @@ public void testPrettyPrintArray() throws IOException { + " 9.0\n" + " ]\n" + "]"; - assertEquals(expected, stringWriter.toString()); + assertThat(stringWriter.toString()).isEqualTo(expected); } @Test @@ -750,7 +748,7 @@ public void testLenientWriterPermitsMultipleTopLevelValues() throws IOException writer.beginArray(); writer.endArray(); writer.close(); - assertEquals("[][]", stringWriter.toString()); + assertThat(stringWriter.toString()).isEqualTo("[][]"); } @Test From c941f90a5bec8ce5e858f0cfd35066413baadc43 Mon Sep 17 00:00:00 2001 From: maicolAntali Date: Sun, 22 Jan 2023 15:38:46 +0100 Subject: [PATCH 02/14] Port Junit assert to Truth in `com.google.gson.regression` --- .../google/gson/regression/JsonAdapterNullSafeTest.java | 8 ++++---- .../test/java/com/google/gson/regression/OSGiTest.java | 6 +++--- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/gson/src/test/java/com/google/gson/regression/JsonAdapterNullSafeTest.java b/gson/src/test/java/com/google/gson/regression/JsonAdapterNullSafeTest.java index a14faff3d1..354f2fd389 100644 --- a/gson/src/test/java/com/google/gson/regression/JsonAdapterNullSafeTest.java +++ b/gson/src/test/java/com/google/gson/regression/JsonAdapterNullSafeTest.java @@ -15,7 +15,7 @@ */ package com.google.gson.regression; -import static org.junit.Assert.assertEquals; +import static com.google.common.truth.Truth.assertThat; import com.google.gson.Gson; import com.google.gson.TypeAdapter; @@ -28,15 +28,15 @@ public class JsonAdapterNullSafeTest { private final Gson gson = new Gson(); @Test - public void testNullSafeBugSerialize() throws Exception { + public void testNullSafeBugSerialize() { Device device = new Device("ec57803e"); gson.toJson(device); } @Test - public void testNullSafeBugDeserialize() throws Exception { + public void testNullSafeBugDeserialize() { Device device = gson.fromJson("{'id':'ec57803e2'}", Device.class); - assertEquals("ec57803e2", device.id); + assertThat(device.id).isEqualTo("ec57803e2"); } @JsonAdapter(Device.JsonAdapterFactory.class) diff --git a/gson/src/test/java/com/google/gson/regression/OSGiTest.java b/gson/src/test/java/com/google/gson/regression/OSGiTest.java index 9512241c79..000a6731ce 100644 --- a/gson/src/test/java/com/google/gson/regression/OSGiTest.java +++ b/gson/src/test/java/com/google/gson/regression/OSGiTest.java @@ -15,7 +15,7 @@ */ package com.google.gson.regression; -import static org.junit.Assert.assertNotNull; +import static com.google.common.truth.Truth.assertWithMessage; import static org.junit.Assert.fail; import java.io.IOException; @@ -32,7 +32,7 @@ public class OSGiTest { public void testComGoogleGsonAnnotationsPackage() throws Exception { Manifest mf = findManifest("com.google.gson"); String importPkg = mf.getMainAttributes().getValue("Import-Package"); - assertNotNull("Import-Package statement is there", importPkg); + assertWithMessage("Import-Package statement is there").that(importPkg).isNotNull(); assertSubstring("There should be com.google.gson.annotations dependency", importPkg, "com.google.gson.annotations"); } @@ -40,7 +40,7 @@ public void testComGoogleGsonAnnotationsPackage() throws Exception { public void testSunMiscImportPackage() throws Exception { Manifest mf = findManifest("com.google.gson"); String importPkg = mf.getMainAttributes().getValue("Import-Package"); - assertNotNull("Import-Package statement is there", importPkg); + assertWithMessage("Import-Package statement is there").that(importPkg).isNotNull(); for (String dep : importPkg.split(",")) { if (dep.contains("sun.misc")) { assertSubstring("sun.misc import is optional", dep, "resolution:=optional"); From ba55856cbf4791355f85d741f3415e4c43cfe1b0 Mon Sep 17 00:00:00 2001 From: maicolAntali Date: Sun, 22 Jan 2023 15:48:47 +0100 Subject: [PATCH 03/14] Port Junit assert to Truth in `om.google.gson.reflect` --- .../google/gson/reflect/TypeTokenTest.java | 100 ++++++++---------- 1 file changed, 46 insertions(+), 54 deletions(-) diff --git a/gson/src/test/java/com/google/gson/reflect/TypeTokenTest.java b/gson/src/test/java/com/google/gson/reflect/TypeTokenTest.java index 89c5c4c31f..52b2988d9d 100644 --- a/gson/src/test/java/com/google/gson/reflect/TypeTokenTest.java +++ b/gson/src/test/java/com/google/gson/reflect/TypeTokenTest.java @@ -16,9 +16,7 @@ package com.google.gson.reflect; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.fail; import java.lang.reflect.GenericArrayType; @@ -45,10 +43,10 @@ public final class TypeTokenTest { @SuppressWarnings({"deprecation"}) @Test public void testIsAssignableFromRawTypes() { - assertTrue(TypeToken.get(Object.class).isAssignableFrom(String.class)); - assertFalse(TypeToken.get(String.class).isAssignableFrom(Object.class)); - assertTrue(TypeToken.get(RandomAccess.class).isAssignableFrom(ArrayList.class)); - assertFalse(TypeToken.get(ArrayList.class).isAssignableFrom(RandomAccess.class)); + assertThat(TypeToken.get(Object.class).isAssignableFrom(String.class)).isTrue(); + assertThat(TypeToken.get(String.class).isAssignableFrom(Object.class)).isFalse(); + assertThat(TypeToken.get(RandomAccess.class).isAssignableFrom(ArrayList.class)).isTrue(); + assertThat(TypeToken.get(ArrayList.class).isAssignableFrom(RandomAccess.class)).isFalse(); } @SuppressWarnings({"deprecation"}) @@ -56,13 +54,13 @@ public void testIsAssignableFromRawTypes() { public void testIsAssignableFromWithTypeParameters() throws Exception { Type a = getClass().getDeclaredField("listOfInteger").getGenericType(); Type b = getClass().getDeclaredField("listOfNumber").getGenericType(); - assertTrue(TypeToken.get(a).isAssignableFrom(a)); - assertTrue(TypeToken.get(b).isAssignableFrom(b)); + assertThat(TypeToken.get(a).isAssignableFrom(a)).isTrue(); + assertThat(TypeToken.get(b).isAssignableFrom(b)).isTrue(); // listOfInteger = listOfNumber; // doesn't compile; must be false - assertFalse(TypeToken.get(a).isAssignableFrom(b)); + assertThat(TypeToken.get(a).isAssignableFrom(b)).isFalse(); // listOfNumber = listOfInteger; // doesn't compile; must be false - assertFalse(TypeToken.get(b).isAssignableFrom(a)); + assertThat(TypeToken.get(b).isAssignableFrom(a)).isFalse(); } @SuppressWarnings({"deprecation"}) @@ -70,14 +68,14 @@ public void testIsAssignableFromWithTypeParameters() throws Exception { public void testIsAssignableFromWithBasicWildcards() throws Exception { Type a = getClass().getDeclaredField("listOfString").getGenericType(); Type b = getClass().getDeclaredField("listOfUnknown").getGenericType(); - assertTrue(TypeToken.get(a).isAssignableFrom(a)); - assertTrue(TypeToken.get(b).isAssignableFrom(b)); + assertThat(TypeToken.get(a).isAssignableFrom(a)).isTrue(); + assertThat(TypeToken.get(b).isAssignableFrom(b)).isTrue(); // listOfString = listOfUnknown // doesn't compile; must be false - assertFalse(TypeToken.get(a).isAssignableFrom(b)); + assertThat(TypeToken.get(a).isAssignableFrom(b)).isFalse(); listOfUnknown = listOfString; // compiles; must be true // The following assertion is too difficult to support reliably, so disabling - // assertTrue(TypeToken.get(b).isAssignableFrom(a)); + // assertThat(TypeToken.get(b).isAssignableFrom(a)).isTrue(); } @SuppressWarnings({"deprecation"}) @@ -85,23 +83,23 @@ public void testIsAssignableFromWithBasicWildcards() throws Exception { public void testIsAssignableFromWithNestedWildcards() throws Exception { Type a = getClass().getDeclaredField("listOfSetOfString").getGenericType(); Type b = getClass().getDeclaredField("listOfSetOfUnknown").getGenericType(); - assertTrue(TypeToken.get(a).isAssignableFrom(a)); - assertTrue(TypeToken.get(b).isAssignableFrom(b)); + assertThat(TypeToken.get(a).isAssignableFrom(a)).isTrue(); + assertThat(TypeToken.get(b).isAssignableFrom(b)).isTrue(); // listOfSetOfString = listOfSetOfUnknown; // doesn't compile; must be false - assertFalse(TypeToken.get(a).isAssignableFrom(b)); + assertThat(TypeToken.get(a).isAssignableFrom(b)).isFalse(); // listOfSetOfUnknown = listOfSetOfString; // doesn't compile; must be false - assertFalse(TypeToken.get(b).isAssignableFrom(a)); + assertThat(TypeToken.get(b).isAssignableFrom(a)).isFalse(); } @Test public void testArrayFactory() { TypeToken expectedStringArray = new TypeToken() {}; - assertEquals(expectedStringArray, TypeToken.getArray(String.class)); + assertThat(TypeToken.getArray(String.class)).isEqualTo(expectedStringArray); TypeToken expectedListOfStringArray = new TypeToken[]>() {}; Type listOfString = new TypeToken>() {}.getType(); - assertEquals(expectedListOfStringArray, TypeToken.getArray(listOfString)); + assertThat(TypeToken.getArray(listOfString)).isEqualTo(expectedListOfStringArray); try { TypeToken.getArray(null); @@ -113,24 +111,24 @@ public void testArrayFactory() { @Test public void testParameterizedFactory() { TypeToken expectedListOfString = new TypeToken>() {}; - assertEquals(expectedListOfString, TypeToken.getParameterized(List.class, String.class)); + assertThat(TypeToken.getParameterized(List.class, String.class)).isEqualTo(expectedListOfString); TypeToken expectedMapOfStringToString = new TypeToken>() {}; - assertEquals(expectedMapOfStringToString, TypeToken.getParameterized(Map.class, String.class, String.class)); + assertThat(TypeToken.getParameterized(Map.class, String.class, String.class)).isEqualTo(expectedMapOfStringToString); TypeToken expectedListOfListOfListOfString = new TypeToken>>>() {}; Type listOfString = TypeToken.getParameterized(List.class, String.class).getType(); Type listOfListOfString = TypeToken.getParameterized(List.class, listOfString).getType(); - assertEquals(expectedListOfListOfListOfString, TypeToken.getParameterized(List.class, listOfListOfString)); + assertThat(TypeToken.getParameterized(List.class, listOfListOfString)).isEqualTo(expectedListOfListOfListOfString); TypeToken expectedWithExactArg = new TypeToken>() {}; - assertEquals(expectedWithExactArg, TypeToken.getParameterized(GenericWithBound.class, Number.class)); + assertThat(TypeToken.getParameterized(GenericWithBound.class, Number.class)).isEqualTo(expectedWithExactArg); TypeToken expectedWithSubclassArg = new TypeToken>() {}; - assertEquals(expectedWithSubclassArg, TypeToken.getParameterized(GenericWithBound.class, Integer.class)); + assertThat(TypeToken.getParameterized(GenericWithBound.class, Integer.class)).isEqualTo(expectedWithSubclassArg); TypeToken expectedSatisfyingTwoBounds = new TypeToken>() {}; - assertEquals(expectedSatisfyingTwoBounds, TypeToken.getParameterized(GenericWithMultiBound.class, ClassSatisfyingBounds.class)); + assertThat(TypeToken.getParameterized(GenericWithMultiBound.class, ClassSatisfyingBounds.class)).isEqualTo(expectedSatisfyingTwoBounds); } @Test @@ -146,73 +144,68 @@ public void testParameterizedFactory_Invalid() { TypeToken.getParameterized(arrayType, new Type[0]); fail(); } catch (IllegalArgumentException e) { - assertEquals("rawType must be of type Class, but was java.lang.String[]", e.getMessage()); + assertThat(e).hasMessageThat().isEqualTo("rawType must be of type Class, but was java.lang.String[]"); } try { TypeToken.getParameterized(String.class, String.class); fail(); } catch (IllegalArgumentException e) { - assertEquals("java.lang.String requires 0 type arguments, but got 1", e.getMessage()); + assertThat(e).hasMessageThat().isEqualTo("java.lang.String requires 0 type arguments, but got 1"); } try { TypeToken.getParameterized(List.class, new Type[0]); fail(); } catch (IllegalArgumentException e) { - assertEquals("java.util.List requires 1 type arguments, but got 0", e.getMessage()); + assertThat(e).hasMessageThat().isEqualTo("java.util.List requires 1 type arguments, but got 0"); } try { TypeToken.getParameterized(List.class, String.class, String.class); fail(); } catch (IllegalArgumentException e) { - assertEquals("java.util.List requires 1 type arguments, but got 2", e.getMessage()); + assertThat(e).hasMessageThat().isEqualTo("java.util.List requires 1 type arguments, but got 2"); } try { TypeToken.getParameterized(GenericWithBound.class, String.class); fail(); } catch (IllegalArgumentException e) { - assertEquals("Type argument class java.lang.String does not satisfy bounds " - + "for type variable T declared by " + GenericWithBound.class, - e.getMessage()); + assertThat(e).hasMessageThat().isEqualTo("Type argument class java.lang.String does not satisfy bounds " + + "for type variable T declared by " + GenericWithBound.class); } try { TypeToken.getParameterized(GenericWithBound.class, Object.class); fail(); } catch (IllegalArgumentException e) { - assertEquals("Type argument class java.lang.Object does not satisfy bounds " - + "for type variable T declared by " + GenericWithBound.class, - e.getMessage()); + assertThat(e).hasMessageThat().isEqualTo("Type argument class java.lang.Object does not satisfy bounds " + + "for type variable T declared by " + GenericWithBound.class); } try { TypeToken.getParameterized(GenericWithMultiBound.class, Number.class); fail(); } catch (IllegalArgumentException e) { - assertEquals("Type argument class java.lang.Number does not satisfy bounds " - + "for type variable T declared by " + GenericWithMultiBound.class, - e.getMessage()); + assertThat(e).hasMessageThat().isEqualTo("Type argument class java.lang.Number does not satisfy bounds " + + "for type variable T declared by " + GenericWithMultiBound.class); } try { TypeToken.getParameterized(GenericWithMultiBound.class, CharSequence.class); fail(); } catch (IllegalArgumentException e) { - assertEquals("Type argument interface java.lang.CharSequence does not satisfy bounds " - + "for type variable T declared by " + GenericWithMultiBound.class, - e.getMessage()); + assertThat(e).hasMessageThat().isEqualTo("Type argument interface java.lang.CharSequence does not satisfy bounds " + + "for type variable T declared by " + GenericWithMultiBound.class); } try { TypeToken.getParameterized(GenericWithMultiBound.class, Object.class); fail(); } catch (IllegalArgumentException e) { - assertEquals("Type argument class java.lang.Object does not satisfy bounds " - + "for type variable T declared by " + GenericWithMultiBound.class, - e.getMessage()); + assertThat(e).hasMessageThat().isEqualTo("Type argument class java.lang.Object does not satisfy bounds " + + "for type variable T declared by " + GenericWithMultiBound.class); } } @@ -222,8 +215,8 @@ private static class CustomTypeToken extends TypeToken { @Test public void testTypeTokenNonAnonymousSubclass() { TypeToken typeToken = new CustomTypeToken(); - assertEquals(String.class, typeToken.getRawType()); - assertEquals(String.class, typeToken.getType()); + assertThat(typeToken.getRawType()).isEqualTo(String.class); + assertThat(typeToken.getType()).isEqualTo(String.class); } /** @@ -240,21 +233,21 @@ class SubSubTypeToken2 extends SubTypeToken {} new SubTypeToken() {}; fail(); } catch (IllegalStateException expected) { - assertEquals("Must only create direct subclasses of TypeToken", expected.getMessage()); + assertThat(expected.getMessage()).isEqualTo("Must only create direct subclasses of TypeToken"); } try { new SubSubTypeToken1(); fail(); } catch (IllegalStateException expected) { - assertEquals("Must only create direct subclasses of TypeToken", expected.getMessage()); + assertThat(expected.getMessage()).isEqualTo("Must only create direct subclasses of TypeToken"); } try { new SubSubTypeToken2(); fail(); } catch (IllegalStateException expected) { - assertEquals("Must only create direct subclasses of TypeToken", expected.getMessage()); + assertThat(expected.getMessage()).isEqualTo("Must only create direct subclasses of TypeToken"); } } @@ -265,9 +258,8 @@ public void testTypeTokenRaw() { new TypeToken() {}; fail(); } catch (IllegalStateException expected) { - assertEquals("TypeToken must be created with a type argument: new TypeToken<...>() {}; " - + "When using code shrinkers (ProGuard, R8, ...) make sure that generic signatures are preserved.", - expected.getMessage()); + assertThat(expected).hasMessageThat().isEqualTo("TypeToken must be created with a type argument: new TypeToken<...>() {}; " + + "When using code shrinkers (ProGuard, R8, ...) make sure that generic signatures are preserved."); } } } From a0138888f891322357b9fd32af4e9020b99cf5f1 Mon Sep 17 00:00:00 2001 From: maicolAntali Date: Sun, 22 Jan 2023 15:50:46 +0100 Subject: [PATCH 04/14] Port Junit assert to Truth in `com.google.gson.metrics` --- .../java/com/google/gson/metrics/PerformanceTest.java | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/gson/src/test/java/com/google/gson/metrics/PerformanceTest.java b/gson/src/test/java/com/google/gson/metrics/PerformanceTest.java index 5670506b8d..abeb1d69b1 100644 --- a/gson/src/test/java/com/google/gson/metrics/PerformanceTest.java +++ b/gson/src/test/java/com/google/gson/metrics/PerformanceTest.java @@ -16,8 +16,7 @@ package com.google.gson.metrics; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static com.google.common.truth.Truth.assertThat; import com.google.gson.Gson; import com.google.gson.JsonParseException; @@ -78,8 +77,8 @@ public void disabled_testStringDeserialization() { private void parseLongJson(String json) throws JsonParseException { ExceptionHolder target = gson.fromJson(json, ExceptionHolder.class); - assertTrue(target.message.contains("Error")); - assertTrue(target.stackTrace.contains("Yippie")); + assertThat(target.message.contains("Error")).isTrue(); + assertThat(target.stackTrace.contains("Yippie")).isTrue(); } private static class ExceptionHolder { @@ -149,7 +148,7 @@ public void disabled_testLargeCollectionDeserialization() { String json = sb.toString(); Type collectionType = new TypeToken>(){}.getType(); List list = gson.fromJson(json, collectionType); - assertEquals(count, list.size()); + assertThat(list).hasSize(count); } /** From 36b9b58438a96eccd2c948b0508b43fb3ba4dce1 Mon Sep 17 00:00:00 2001 From: maicolAntali Date: Wed, 25 Jan 2023 14:54:13 +0100 Subject: [PATCH 05/14] Port Junit assert to Truth in `com.google.gson.internal` --- .../internal/ConstructorConstructorTest.java | 18 ++--- .../gson/internal/GsonBuildConfigTest.java | 4 +- .../google/gson/internal/GsonTypesTest.java | 13 ++-- .../google/gson/internal/JavaVersionTest.java | 39 +++++----- .../gson/internal/LazilyParsedNumberTest.java | 9 +-- .../gson/internal/LinkedTreeMapTest.java | 78 +++++++++---------- .../com/google/gson/internal/StreamsTest.java | 6 +- .../UnsafeAllocatorInstantiationTest.java | 9 +-- 8 files changed, 83 insertions(+), 93 deletions(-) diff --git a/gson/src/test/java/com/google/gson/internal/ConstructorConstructorTest.java b/gson/src/test/java/com/google/gson/internal/ConstructorConstructorTest.java index ba3c339aa1..7ca2f89987 100644 --- a/gson/src/test/java/com/google/gson/internal/ConstructorConstructorTest.java +++ b/gson/src/test/java/com/google/gson/internal/ConstructorConstructorTest.java @@ -1,6 +1,6 @@ package com.google.gson.internal; -import static org.junit.Assert.assertEquals; +import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.fail; import com.google.gson.InstanceCreator; @@ -33,11 +33,9 @@ public void testGet_AbstractClassNoArgConstructor() { constructor.construct(); fail("Expected exception"); } catch (RuntimeException exception) { - assertEquals( - "Abstract classes can't be instantiated! Register an InstanceCreator or a TypeAdapter for this " - + "type. Class name: com.google.gson.internal.ConstructorConstructorTest$AbstractClass", - exception.getMessage() - ); + assertThat(exception).hasMessageThat().isEqualTo("Abstract classes can't be instantiated! " + + "Register an InstanceCreator or a TypeAdapter for this type. " + + "Class name: com.google.gson.internal.ConstructorConstructorTest$AbstractClass"); } } @@ -48,11 +46,9 @@ public void testGet_Interface() { constructor.construct(); fail("Expected exception"); } catch (RuntimeException exception) { - assertEquals( - "Interfaces can't be instantiated! Register an InstanceCreator or a TypeAdapter for " - + "this type. Interface name: com.google.gson.internal.ConstructorConstructorTest$Interface", - exception.getMessage() - ); + assertThat(exception).hasMessageThat().isEqualTo("Interfaces can't be instantiated! " + + "Register an InstanceCreator or a TypeAdapter for this type. " + + "Interface name: com.google.gson.internal.ConstructorConstructorTest$Interface"); } } } diff --git a/gson/src/test/java/com/google/gson/internal/GsonBuildConfigTest.java b/gson/src/test/java/com/google/gson/internal/GsonBuildConfigTest.java index dc39bc02df..a1af3a0861 100644 --- a/gson/src/test/java/com/google/gson/internal/GsonBuildConfigTest.java +++ b/gson/src/test/java/com/google/gson/internal/GsonBuildConfigTest.java @@ -15,7 +15,7 @@ */ package com.google.gson.internal; -import static org.junit.Assert.assertFalse; +import static com.google.common.truth.Truth.assertThat; import org.junit.Test; @@ -28,6 +28,6 @@ public class GsonBuildConfigTest { @Test public void testEnsureGsonBuildConfigGetsUpdatedToMavenVersion() { - assertFalse("${project.version}".equals(GsonBuildConfig.VERSION)); + assertThat("${project.version}").isNotEqualTo(GsonBuildConfig.VERSION); } } diff --git a/gson/src/test/java/com/google/gson/internal/GsonTypesTest.java b/gson/src/test/java/com/google/gson/internal/GsonTypesTest.java index dd45e87f29..af824975c5 100644 --- a/gson/src/test/java/com/google/gson/internal/GsonTypesTest.java +++ b/gson/src/test/java/com/google/gson/internal/GsonTypesTest.java @@ -16,8 +16,7 @@ package com.google.gson.internal; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.fail; import java.lang.reflect.ParameterizedType; @@ -31,11 +30,11 @@ public final class GsonTypesTest { public void testNewParameterizedTypeWithoutOwner() throws Exception { // List. List is a top-level class Type type = $Gson$Types.newParameterizedTypeWithOwner(null, List.class, A.class); - assertEquals(A.class, getFirstTypeArgument(type)); + assertThat(getFirstTypeArgument(type)).isEqualTo(A.class); // A. A is a static inner class. type = $Gson$Types.newParameterizedTypeWithOwner(null, A.class, B.class); - assertEquals(B.class, getFirstTypeArgument(type)); + assertThat(getFirstTypeArgument(type)).isEqualTo(B.class); final class D { } @@ -47,15 +46,15 @@ final class D { // A is allowed. type = $Gson$Types.newParameterizedTypeWithOwner(null, A.class, D.class); - assertEquals(D.class, getFirstTypeArgument(type)); + assertThat(getFirstTypeArgument(type)).isEqualTo(D.class); } @Test public void testGetFirstTypeArgument() throws Exception { - assertNull(getFirstTypeArgument(A.class)); + assertThat(getFirstTypeArgument(A.class)).isNull(); Type type = $Gson$Types.newParameterizedTypeWithOwner(null, A.class, B.class, C.class); - assertEquals(B.class, getFirstTypeArgument(type)); + assertThat(getFirstTypeArgument(type)).isEqualTo(B.class); } private static final class A { diff --git a/gson/src/test/java/com/google/gson/internal/JavaVersionTest.java b/gson/src/test/java/com/google/gson/internal/JavaVersionTest.java index 582d683a41..e2e9ea6a2e 100644 --- a/gson/src/test/java/com/google/gson/internal/JavaVersionTest.java +++ b/gson/src/test/java/com/google/gson/internal/JavaVersionTest.java @@ -15,8 +15,7 @@ */ package com.google.gson.internal; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static com.google.common.truth.Truth.assertThat; import org.junit.Test; @@ -30,51 +29,51 @@ public class JavaVersionTest { @Test public void testGetMajorJavaVersion() { - assertTrue(JavaVersion.getMajorJavaVersion() >= 7); // Gson currently requires at least Java 7 + assertThat(JavaVersion.getMajorJavaVersion() >= 7).isTrue(); // Gson currently requires at least Java 7 } @Test public void testJava6() { - assertEquals(6, JavaVersion.getMajorJavaVersion("1.6.0")); // http://www.oracle.com/technetwork/java/javase/version-6-141920.html + assertThat(JavaVersion.getMajorJavaVersion("1.6.0")).isEqualTo(6); // http://www.oracle.com/technetwork/java/javase/version-6-141920.html } @Test public void testJava7() { - assertEquals(7, JavaVersion.getMajorJavaVersion("1.7.0")); // http://www.oracle.com/technetwork/java/javase/jdk7-naming-418744.html + assertThat(JavaVersion.getMajorJavaVersion("1.7.0")).isEqualTo(7); // http://www.oracle.com/technetwork/java/javase/jdk7-naming-418744.html } @Test public void testJava8() { - assertEquals(8, JavaVersion.getMajorJavaVersion("1.8")); - assertEquals(8, JavaVersion.getMajorJavaVersion("1.8.0")); - assertEquals(8, JavaVersion.getMajorJavaVersion("1.8.0_131")); - assertEquals(8, JavaVersion.getMajorJavaVersion("1.8.0_60-ea")); - assertEquals(8, JavaVersion.getMajorJavaVersion("1.8.0_111-internal")); + assertThat(JavaVersion.getMajorJavaVersion("1.8")).isEqualTo(8); + assertThat(JavaVersion.getMajorJavaVersion("1.8.0")).isEqualTo(8); + assertThat(JavaVersion.getMajorJavaVersion("1.8.0_131")).isEqualTo(8); + assertThat(JavaVersion.getMajorJavaVersion("1.8.0_60-ea")).isEqualTo(8); + assertThat(JavaVersion.getMajorJavaVersion("1.8.0_111-internal")).isEqualTo(8); // openjdk8 per https://github.com/AdoptOpenJDK/openjdk-build/issues/93 - assertEquals(8, JavaVersion.getMajorJavaVersion("1.8.0-internal")); - assertEquals(8, JavaVersion.getMajorJavaVersion("1.8.0_131-adoptopenjdk")); + assertThat(JavaVersion.getMajorJavaVersion("1.8.0-internal")).isEqualTo(8); + assertThat(JavaVersion.getMajorJavaVersion("1.8.0_131-adoptopenjdk")).isEqualTo(8); } @Test public void testJava9() { // Legacy style - assertEquals(9, JavaVersion.getMajorJavaVersion("9.0.4")); // Oracle JDK 9 - assertEquals(9, JavaVersion.getMajorJavaVersion("9-Debian")); // Debian as reported in https://github.com/google/gson/issues/1310 + assertThat(JavaVersion.getMajorJavaVersion("9.0.4")).isEqualTo(9); // Oracle JDK 9 + assertThat(JavaVersion.getMajorJavaVersion("9-Debian")).isEqualTo(9); // Debian as reported in https://github.com/google/gson/issues/1310 // New style - assertEquals(9, JavaVersion.getMajorJavaVersion("9-ea+19")); - assertEquals(9, JavaVersion.getMajorJavaVersion("9+100")); - assertEquals(9, JavaVersion.getMajorJavaVersion("9.0.1+20")); - assertEquals(9, JavaVersion.getMajorJavaVersion("9.1.1+20")); + assertThat(JavaVersion.getMajorJavaVersion("9-ea+19")).isEqualTo(9); + assertThat(JavaVersion.getMajorJavaVersion("9+100")).isEqualTo(9); + assertThat(JavaVersion.getMajorJavaVersion("9.0.1+20")).isEqualTo(9); + assertThat(JavaVersion.getMajorJavaVersion("9.1.1+20")).isEqualTo(9); } @Test public void testJava10() { - assertEquals(10, JavaVersion.getMajorJavaVersion("10.0.1")); // Oracle JDK 10.0.1 + assertThat(JavaVersion.getMajorJavaVersion("10.0.1")).isEqualTo(10); // Oracle JDK 10.0.1 } @Test public void testUnknownVersionFormat() { - assertEquals(6, JavaVersion.getMajorJavaVersion("Java9")); // unknown format + assertThat(JavaVersion.getMajorJavaVersion("Java9")).isEqualTo(6); // unknown format } } diff --git a/gson/src/test/java/com/google/gson/internal/LazilyParsedNumberTest.java b/gson/src/test/java/com/google/gson/internal/LazilyParsedNumberTest.java index f4f207f26b..e47f2ee05a 100644 --- a/gson/src/test/java/com/google/gson/internal/LazilyParsedNumberTest.java +++ b/gson/src/test/java/com/google/gson/internal/LazilyParsedNumberTest.java @@ -15,8 +15,7 @@ */ package com.google.gson.internal; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static com.google.common.truth.Truth.assertThat; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -31,14 +30,14 @@ public class LazilyParsedNumberTest { public void testHashCode() { LazilyParsedNumber n1 = new LazilyParsedNumber("1"); LazilyParsedNumber n1Another = new LazilyParsedNumber("1"); - assertEquals(n1.hashCode(), n1Another.hashCode()); + assertThat(n1Another.hashCode()).isEqualTo(n1.hashCode()); } @Test public void testEquals() { LazilyParsedNumber n1 = new LazilyParsedNumber("1"); LazilyParsedNumber n1Another = new LazilyParsedNumber("1"); - assertTrue(n1.equals(n1Another)); + assertThat(n1.equals(n1Another)).isTrue(); } @Test @@ -50,6 +49,6 @@ public void testJavaSerialization() throws IOException, ClassNotFoundException { ObjectInputStream objIn = new ObjectInputStream(new ByteArrayInputStream(out.toByteArray())); Number deserialized = (Number) objIn.readObject(); - assertEquals(new BigDecimal("123"), deserialized); + assertThat(deserialized).isEqualTo(new BigDecimal("123")); } } diff --git a/gson/src/test/java/com/google/gson/internal/LinkedTreeMapTest.java b/gson/src/test/java/com/google/gson/internal/LinkedTreeMapTest.java index 89154ae4bb..c811e31b12 100644 --- a/gson/src/test/java/com/google/gson/internal/LinkedTreeMapTest.java +++ b/gson/src/test/java/com/google/gson/internal/LinkedTreeMapTest.java @@ -16,10 +16,7 @@ package com.google.gson.internal; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.fail; import com.google.gson.common.MoreAsserts; @@ -86,10 +83,11 @@ public void testPutNonComparableKeyFails() { public void testPutNullValue() { LinkedTreeMap map = new LinkedTreeMap<>(); map.put("a", null); - assertEquals(1, map.size()); - assertTrue(map.containsKey("a")); - assertTrue(map.containsValue(null)); - assertNull(map.get("a")); + + assertThat(map).hasSize(1); + assertThat(map.containsKey("a")).isTrue(); + assertThat(map.containsValue(null)).isTrue(); + assertThat(map.get("a")).isNull(); } @Test @@ -99,27 +97,27 @@ public void testPutNullValue_Forbidden() { map.put("a", null); fail(); } catch (NullPointerException e) { - assertEquals("value == null", e.getMessage()); + assertThat(e.getMessage()).isEqualTo("value == null"); } - assertEquals(0, map.size()); - assertFalse(map.containsKey("a")); - assertFalse(map.containsValue(null)); + assertThat(map).hasSize(0); + assertThat(map).doesNotContainKey("a"); + assertThat(map.containsValue(null)).isFalse(); } @Test public void testEntrySetValueNull() { LinkedTreeMap map = new LinkedTreeMap<>(); map.put("a", "1"); - assertEquals("1", map.get("a")); + assertThat(map.get("a")).isEqualTo("1"); Entry entry = map.entrySet().iterator().next(); - assertEquals("a", entry.getKey()); - assertEquals("1", entry.getValue()); + assertThat(entry.getKey()).isEqualTo("a"); + assertThat(entry.getValue()).isEqualTo("1"); entry.setValue(null); - assertNull(entry.getValue()); + assertThat(entry.getValue()).isNull(); - assertTrue(map.containsKey("a")); - assertTrue(map.containsValue(null)); - assertNull(map.get("a")); + assertThat(map.containsKey("a")).isTrue(); + assertThat(map.containsValue(null)).isTrue(); + assertThat(map.get("a")).isNull(); } @@ -132,47 +130,47 @@ public void testEntrySetValueNull_Forbidden() { entry.setValue(null); fail(); } catch (NullPointerException e) { - assertEquals("value == null", e.getMessage()); + assertThat(e.getMessage()).isEqualTo("value == null"); } - assertEquals("1", entry.getValue()); - assertEquals("1", map.get("a")); - assertFalse(map.containsValue(null)); + assertThat(entry.getValue()).isEqualTo("1"); + assertThat(map.get("a")).isEqualTo("1"); + assertThat(map.containsValue(null)).isFalse(); } @Test public void testContainsNonComparableKeyReturnsFalse() { LinkedTreeMap map = new LinkedTreeMap<>(); map.put("a", "android"); - assertFalse(map.containsKey(new Object())); + assertThat(map).doesNotContainKey(new Object()); } @Test public void testContainsNullKeyIsAlwaysFalse() { LinkedTreeMap map = new LinkedTreeMap<>(); - assertFalse(map.containsKey(null)); + assertThat(map.containsKey(null)).isFalse(); map.put("a", "android"); - assertFalse(map.containsKey(null)); + assertThat(map.containsKey(null)).isFalse(); } @Test public void testPutOverrides() throws Exception { LinkedTreeMap map = new LinkedTreeMap<>(); - assertNull(map.put("d", "donut")); - assertNull(map.put("e", "eclair")); - assertNull(map.put("f", "froyo")); - assertEquals(3, map.size()); + assertThat(map.put("d", "donut")).isNull(); + assertThat(map.put("e", "eclair")).isNull(); + assertThat(map.put("f", "froyo")).isNull(); + assertThat(map).hasSize(3); - assertEquals("donut", map.get("d")); - assertEquals("donut", map.put("d", "done")); - assertEquals(3, map.size()); + assertThat(map.get("d")).isEqualTo("donut"); + assertThat(map.put("d", "done")).isEqualTo("donut"); + assertThat(map).hasSize(3); } @Test public void testEmptyStringValues() { LinkedTreeMap map = new LinkedTreeMap<>(); map.put("a", ""); - assertTrue(map.containsKey("a")); - assertEquals("", map.get("a")); + assertThat(map.containsKey("a")).isTrue(); + assertThat(map.get("a")).isEqualTo(""); } @Test @@ -187,8 +185,8 @@ public void testLargeSetOfRandomKeys() throws Exception { for (int i = 0; i < keys.length; i++) { String key = keys[i]; - assertTrue(map.containsKey(key)); - assertEquals("" + i, map.get(key)); + assertThat(map.containsKey(key)).isTrue(); + assertThat(map.get(key)).isEqualTo("" + i); } } @@ -200,7 +198,7 @@ public void testClear() { map.put("b", "bbq"); map.clear(); assertIterationOrder(map.keySet()); - assertEquals(0, map.size()); + assertThat(map).hasSize(0); } @Test @@ -232,7 +230,7 @@ public void testJavaSerialization() throws IOException, ClassNotFoundException { ObjectInputStream objIn = new ObjectInputStream(new ByteArrayInputStream(out.toByteArray())); @SuppressWarnings("unchecked") Map deserialized = (Map) objIn.readObject(); - assertEquals(Collections.singletonMap("a", 1), deserialized); + assertThat(deserialized).isEqualTo(Collections.singletonMap("a", 1)); } @SuppressWarnings("varargs") @@ -242,6 +240,6 @@ private final void assertIterationOrder(Iterable actual, T... expected) { for (T t : actual) { actualList.add(t); } - assertEquals(Arrays.asList(expected), actualList); + assertThat(actualList).isEqualTo(Arrays.asList(expected)); } } diff --git a/gson/src/test/java/com/google/gson/internal/StreamsTest.java b/gson/src/test/java/com/google/gson/internal/StreamsTest.java index d0cb90aa5b..61b4215585 100644 --- a/gson/src/test/java/com/google/gson/internal/StreamsTest.java +++ b/gson/src/test/java/com/google/gson/internal/StreamsTest.java @@ -1,6 +1,6 @@ package com.google.gson.internal; -import static org.junit.Assert.assertEquals; +import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.fail; import java.io.IOException; @@ -57,12 +57,12 @@ public void testWriterForAppendable() throws IOException { } String actualOutput = stringBuilder.toString(); - assertEquals("a\u1234testnullcdul,a\u1234\u1234,charsha,stringtr", actualOutput); + assertThat(actualOutput).isEqualTo("a\u1234testnullcdul,a\u1234\u1234,charsha,stringtr"); writer.flush(); writer.close(); // flush() and close() calls should have had no effect - assertEquals(actualOutput, stringBuilder.toString()); + assertThat(stringBuilder.toString()).isEqualTo(actualOutput); } } diff --git a/gson/src/test/java/com/google/gson/internal/UnsafeAllocatorInstantiationTest.java b/gson/src/test/java/com/google/gson/internal/UnsafeAllocatorInstantiationTest.java index b8ab177d18..a80a4c3d61 100644 --- a/gson/src/test/java/com/google/gson/internal/UnsafeAllocatorInstantiationTest.java +++ b/gson/src/test/java/com/google/gson/internal/UnsafeAllocatorInstantiationTest.java @@ -15,8 +15,7 @@ */ package com.google.gson.internal; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.fail; import org.junit.Test; @@ -46,7 +45,7 @@ public void testInterfaceInstantiation() throws Exception { UnsafeAllocator.INSTANCE.newInstance(Interface.class); fail(); } catch (AssertionError e) { - assertTrue(e.getMessage().startsWith("UnsafeAllocator is used for non-instantiable type")); + assertThat(e).hasMessageThat().startsWith("UnsafeAllocator is used for non-instantiable type"); } } @@ -60,7 +59,7 @@ public void testAbstractClassInstantiation() throws Exception { UnsafeAllocator.INSTANCE.newInstance(AbstractClass.class); fail(); } catch (AssertionError e) { - assertTrue(e.getMessage().startsWith("UnsafeAllocator is used for non-instantiable type")); + assertThat(e).hasMessageThat().startsWith("UnsafeAllocator is used for non-instantiable type"); } } @@ -70,6 +69,6 @@ public void testAbstractClassInstantiation() throws Exception { @Test public void testConcreteClassInstantiation() throws Exception { ConcreteClass instance = UnsafeAllocator.INSTANCE.newInstance(ConcreteClass.class); - assertNotNull(instance); + assertThat(instance).isNotNull(); } } From 38c96653a520a7f4d495318b2d923c2308ca9110 Mon Sep 17 00:00:00 2001 From: maicolAntali Date: Wed, 25 Jan 2023 14:57:22 +0100 Subject: [PATCH 06/14] Port Junit assert to Truth in `com.google.gson.internal.sql` --- .../gson/internal/sql/SqlTypesGsonTest.java | 18 +++++++++--------- .../gson/internal/sql/SqlTypesSupportTest.java | 15 +++++++-------- 2 files changed, 16 insertions(+), 17 deletions(-) diff --git a/gson/src/test/java/com/google/gson/internal/sql/SqlTypesGsonTest.java b/gson/src/test/java/com/google/gson/internal/sql/SqlTypesGsonTest.java index 832e38ca8a..e685a48f92 100644 --- a/gson/src/test/java/com/google/gson/internal/sql/SqlTypesGsonTest.java +++ b/gson/src/test/java/com/google/gson/internal/sql/SqlTypesGsonTest.java @@ -1,6 +1,6 @@ package com.google.gson.internal.sql; -import static org.junit.Assert.assertEquals; +import static com.google.common.truth.Truth.assertThat; import com.google.gson.Gson; import com.google.gson.GsonBuilder; @@ -50,7 +50,7 @@ private void testNullSerializationAndDeserialization(Class c) { public void testDefaultSqlDateSerialization() { java.sql.Date instant = new java.sql.Date(1259875082000L); String json = gson.toJson(instant); - assertEquals("\"Dec 3, 2009\"", json); + assertThat(json).isEqualTo("\"Dec 3, 2009\""); } @Test @@ -71,8 +71,8 @@ public void testSqlDateSerialization() throws Exception { java.sql.Date sqlDate = new java.sql.Date(0L); Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create(); String json = gson.toJson(sqlDate, Timestamp.class); - assertEquals("\"1970-01-01\"", json); - assertEquals(0, gson.fromJson("\"1970-01-01\"", java.sql.Date.class).getTime()); + assertThat(json).isEqualTo("\"1970-01-01\""); + assertThat(gson.fromJson("\"1970-01-01\"", java.sql.Date.class).getTime()).isEqualTo(0); } finally { TimeZone.setDefault(defaultTimeZone); Locale.setDefault(defaultLocale); @@ -83,7 +83,7 @@ public void testSqlDateSerialization() throws Exception { public void testDefaultSqlTimeSerialization() { Time now = new Time(1259875082000L); String json = gson.toJson(now); - assertEquals("\"01:18:02 PM\"", json); + assertThat(json).isEqualTo("\"01:18:02 PM\""); } @Test @@ -98,9 +98,9 @@ public void testDefaultSqlTimestampSerialization() { Timestamp now = new java.sql.Timestamp(1259875082000L); String json = gson.toJson(now); if (JavaVersion.isJava9OrLater()) { - assertEquals("\"Dec 3, 2009, 1:18:02 PM\"", json); + assertThat(json).isEqualTo("\"Dec 3, 2009, 1:18:02 PM\""); } else { - assertEquals("\"Dec 3, 2009 1:18:02 PM\"", json); + assertThat(json).isEqualTo("\"Dec 3, 2009 1:18:02 PM\""); } } @@ -123,8 +123,8 @@ public void testTimestampSerialization() throws Exception { Timestamp timestamp = new Timestamp(0L); Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create(); String json = gson.toJson(timestamp, Timestamp.class); - assertEquals("\"1970-01-01\"", json); - assertEquals(0, gson.fromJson("\"1970-01-01\"", Timestamp.class).getTime()); + assertThat(json).isEqualTo("\"1970-01-01\""); + assertThat(gson.fromJson("\"1970-01-01\"", Timestamp.class).getTime()).isEqualTo(0); } finally { TimeZone.setDefault(defaultTimeZone); Locale.setDefault(defaultLocale); diff --git a/gson/src/test/java/com/google/gson/internal/sql/SqlTypesSupportTest.java b/gson/src/test/java/com/google/gson/internal/sql/SqlTypesSupportTest.java index 51244283cb..d912fd55bf 100644 --- a/gson/src/test/java/com/google/gson/internal/sql/SqlTypesSupportTest.java +++ b/gson/src/test/java/com/google/gson/internal/sql/SqlTypesSupportTest.java @@ -1,20 +1,19 @@ package com.google.gson.internal.sql; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static com.google.common.truth.Truth.assertThat; import org.junit.Test; public class SqlTypesSupportTest { @Test public void testSupported() { - assertTrue(SqlTypesSupport.SUPPORTS_SQL_TYPES); + assertThat(SqlTypesSupport.SUPPORTS_SQL_TYPES).isTrue(); - assertNotNull(SqlTypesSupport.DATE_DATE_TYPE); - assertNotNull(SqlTypesSupport.TIMESTAMP_DATE_TYPE); + assertThat(SqlTypesSupport.DATE_DATE_TYPE).isNotNull(); + assertThat(SqlTypesSupport.TIMESTAMP_DATE_TYPE).isNotNull(); - assertNotNull(SqlTypesSupport.DATE_FACTORY); - assertNotNull(SqlTypesSupport.TIME_FACTORY); - assertNotNull(SqlTypesSupport.TIMESTAMP_FACTORY); + assertThat(SqlTypesSupport.DATE_FACTORY).isNotNull(); + assertThat(SqlTypesSupport.TIME_FACTORY).isNotNull(); + assertThat(SqlTypesSupport.TIMESTAMP_FACTORY).isNotNull(); } } From 4d5ecbc1b009761e39191dd9b185657dfb2f83bf Mon Sep 17 00:00:00 2001 From: maicolAntali Date: Wed, 25 Jan 2023 15:00:31 +0100 Subject: [PATCH 07/14] Port Junit assert to Truth in `com.google.gson.internal.reflect` --- .../reflect/Java17ReflectionHelperTest.java | 21 +++++++------------ 1 file changed, 7 insertions(+), 14 deletions(-) diff --git a/gson/src/test/java/com/google/gson/internal/reflect/Java17ReflectionHelperTest.java b/gson/src/test/java/com/google/gson/internal/reflect/Java17ReflectionHelperTest.java index 4d4089e87a..6d8a7015ed 100644 --- a/gson/src/test/java/com/google/gson/internal/reflect/Java17ReflectionHelperTest.java +++ b/gson/src/test/java/com/google/gson/internal/reflect/Java17ReflectionHelperTest.java @@ -1,9 +1,6 @@ package com.google.gson.internal.reflect; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static com.google.common.truth.Truth.assertThat; import java.lang.reflect.Constructor; import java.lang.reflect.Field; @@ -18,18 +15,14 @@ public class Java17ReflectionHelperTest { public void testJava17Record() throws ClassNotFoundException { Class unixDomainPrincipalClass = Class.forName("jdk.net.UnixDomainPrincipal"); // UnixDomainPrincipal is a record - assertTrue(ReflectionHelper.isRecord(unixDomainPrincipalClass)); + assertThat(ReflectionHelper.isRecord(unixDomainPrincipalClass)).isTrue(); // with 2 components - assertArrayEquals( - new String[] {"user", "group"}, - ReflectionHelper.getRecordComponentNames(unixDomainPrincipalClass)); + assertThat(ReflectionHelper.getRecordComponentNames(unixDomainPrincipalClass)).isEqualTo(new String[] {"user", "group"}); // Check canonical constructor Constructor constructor = ReflectionHelper.getCanonicalRecordConstructor(unixDomainPrincipalClass); - assertNotNull(constructor); - assertArrayEquals( - new Class[] {UserPrincipal.class, GroupPrincipal.class}, - constructor.getParameterTypes()); + assertThat(constructor).isNotNull(); + assertThat(constructor.getParameterTypes()).isEqualTo(new Class[] {UserPrincipal.class, GroupPrincipal.class}); } @Test @@ -43,14 +36,14 @@ public void testJava17RecordAccessors() throws ReflectiveOperationException { .newInstance(new PrincipalImpl("user"), new PrincipalImpl("group")); String[] componentNames = ReflectionHelper.getRecordComponentNames(unixDomainPrincipalClass); - assertTrue(componentNames.length > 0); + assertThat(componentNames.length > 0).isTrue(); for (String componentName : componentNames) { Field componentField = unixDomainPrincipalClass.getDeclaredField(componentName); Method accessor = ReflectionHelper.getAccessor(unixDomainPrincipalClass, componentField); Object principal = accessor.invoke(unixDomainPrincipal); - assertEquals(new PrincipalImpl(componentName), principal); + assertThat(principal).isEqualTo(new PrincipalImpl(componentName)); } } From 6ef058de05cc2a5f5d2ce14d4c3a33792f689a32 Mon Sep 17 00:00:00 2001 From: maicolAntali Date: Wed, 25 Jan 2023 15:23:52 +0100 Subject: [PATCH 08/14] Port Junit assert to Truth in `com.google.gson.internal.bind` --- .../bind/DefaultDateTypeAdapterTest.java | 27 +++-- ...ava17ReflectiveTypeAdapterFactoryTest.java | 9 +- .../internal/bind/JsonElementReaderTest.java | 99 +++++++++---------- .../internal/bind/JsonTreeReaderTest.java | 38 ++++--- .../internal/bind/JsonTreeWriterTest.java | 28 +++--- .../bind/RecursiveTypesResolveTest.java | 29 +++--- 6 files changed, 112 insertions(+), 118 deletions(-) diff --git a/gson/src/test/java/com/google/gson/internal/bind/DefaultDateTypeAdapterTest.java b/gson/src/test/java/com/google/gson/internal/bind/DefaultDateTypeAdapterTest.java index d006eb09eb..99d69e03ad 100644 --- a/gson/src/test/java/com/google/gson/internal/bind/DefaultDateTypeAdapterTest.java +++ b/gson/src/test/java/com/google/gson/internal/bind/DefaultDateTypeAdapterTest.java @@ -16,9 +16,8 @@ package com.google.gson.internal.bind; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static com.google.common.truth.Truth.assertThat; +import static com.google.common.truth.Truth.assertWithMessage; import static org.junit.Assert.fail; import com.google.gson.Gson; @@ -171,29 +170,29 @@ public void testDateDeserializationISO8601() throws Exception { } @Test - public void testDateSerialization() throws Exception { + public void testDateSerialization() { int dateStyle = DateFormat.LONG; TypeAdapter dateTypeAdapter = dateAdapter(DateType.DATE.createAdapterFactory(dateStyle)); DateFormat formatter = DateFormat.getDateInstance(dateStyle, Locale.US); Date currentDate = new Date(); String dateString = dateTypeAdapter.toJson(currentDate); - assertEquals(toLiteral(formatter.format(currentDate)), dateString); + assertThat(dateString).isEqualTo(toLiteral(formatter.format(currentDate))); } @Test - public void testDatePattern() throws Exception { + public void testDatePattern() { String pattern = "yyyy-MM-dd"; TypeAdapter dateTypeAdapter = dateAdapter(DateType.DATE.createAdapterFactory(pattern)); DateFormat formatter = new SimpleDateFormat(pattern); Date currentDate = new Date(); String dateString = dateTypeAdapter.toJson(currentDate); - assertEquals(toLiteral(formatter.format(currentDate)), dateString); + assertThat(dateString).isEqualTo(toLiteral(formatter.format(currentDate))); } @Test - public void testInvalidDatePattern() throws Exception { + public void testInvalidDatePattern() { try { DateType.DATE.createAdapterFactory("I am a bad Date pattern...."); fail("Invalid date pattern should fail."); @@ -203,8 +202,8 @@ public void testInvalidDatePattern() throws Exception { @Test public void testNullValue() throws Exception { TypeAdapter adapter = dateAdapter(DateType.DATE.createDefaultsAdapterFactory()); - assertNull(adapter.fromJson("null")); - assertEquals("null", adapter.toJson(null)); + assertThat(adapter.fromJson("null")).isNull(); + assertThat(adapter.toJson(null)).isEqualTo("null"); } @Test @@ -218,19 +217,19 @@ public void testUnexpectedToken() throws Exception { private static TypeAdapter dateAdapter(TypeAdapterFactory adapterFactory) { TypeAdapter adapter = adapterFactory.create(new Gson(), TypeToken.get(Date.class)); - assertNotNull(adapter); + assertThat(adapter).isNotNull(); return adapter; } private static void assertFormatted(String formatted, TypeAdapterFactory adapterFactory) { TypeAdapter adapter = dateAdapter(adapterFactory); - assertEquals(toLiteral(formatted), adapter.toJson(new Date(0))); + assertThat(adapter.toJson(new Date(0))).isEqualTo(toLiteral(formatted)); } private static void assertParsed(String date, TypeAdapterFactory adapterFactory) throws IOException { TypeAdapter adapter = dateAdapter(adapterFactory); - assertEquals(date, new Date(0), adapter.fromJson(toLiteral(date))); - assertEquals("ISO 8601", new Date(0), adapter.fromJson(toLiteral("1970-01-01T00:00:00Z"))); + assertWithMessage(date).that(adapter.fromJson(toLiteral(date))).isEqualTo(new Date(0)); + assertWithMessage("ISO 8601").that(adapter.fromJson(toLiteral("1970-01-01T00:00:00Z"))).isEqualTo(new Date(0)); } private static String toLiteral(String s) { diff --git a/gson/src/test/java/com/google/gson/internal/bind/Java17ReflectiveTypeAdapterFactoryTest.java b/gson/src/test/java/com/google/gson/internal/bind/Java17ReflectiveTypeAdapterFactoryTest.java index 18984c7b6d..288d1a387c 100644 --- a/gson/src/test/java/com/google/gson/internal/bind/Java17ReflectiveTypeAdapterFactoryTest.java +++ b/gson/src/test/java/com/google/gson/internal/bind/Java17ReflectiveTypeAdapterFactoryTest.java @@ -1,7 +1,6 @@ package com.google.gson.internal.bind; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; +import static com.google.common.truth.Truth.assertThat; import com.google.gson.Gson; import com.google.gson.GsonBuilder; @@ -39,7 +38,7 @@ public void testCustomAdapterForRecords() { Gson gson = new Gson(); TypeAdapter recordAdapter = gson.getAdapter(unixDomainPrincipalClass); TypeAdapter defaultReflectionAdapter = gson.getAdapter(DummyClass.class); - assertNotEquals(recordAdapter.getClass(), defaultReflectionAdapter.getClass()); + assertThat(defaultReflectionAdapter.getClass()).isNotEqualTo(recordAdapter.getClass()); } @Test @@ -59,8 +58,8 @@ public void testSerializeRecords() throws ReflectiveOperationException { String serialized = gson.toJson(recordInstance); Object deserializedRecordInstance = gson.fromJson(serialized, unixDomainPrincipalClass); - assertEquals(recordInstance, deserializedRecordInstance); - assertEquals("{\"user\":\"user\",\"group\":\"group\"}", serialized); + assertThat(deserializedRecordInstance).isEqualTo(recordInstance); + assertThat(serialized).isEqualTo("{\"user\":\"user\",\"group\":\"group\"}"); } private static class PrincipalTypeAdapter extends TypeAdapter { diff --git a/gson/src/test/java/com/google/gson/internal/bind/JsonElementReaderTest.java b/gson/src/test/java/com/google/gson/internal/bind/JsonElementReaderTest.java index efdf7b63c5..b344e6f9ec 100644 --- a/gson/src/test/java/com/google/gson/internal/bind/JsonElementReaderTest.java +++ b/gson/src/test/java/com/google/gson/internal/bind/JsonElementReaderTest.java @@ -16,8 +16,7 @@ package com.google.gson.internal.bind; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.fail; import com.google.gson.JsonElement; @@ -36,9 +35,9 @@ public void testNumbers() throws IOException { JsonElement element = JsonParser.parseString("[1, 2, 3]"); JsonTreeReader reader = new JsonTreeReader(element); reader.beginArray(); - assertEquals(1, reader.nextInt()); - assertEquals(2L, reader.nextLong()); - assertEquals(3.0, reader.nextDouble(), 0); + assertThat(reader.nextInt()).isEqualTo(1); + assertThat(reader.nextLong()).isEqualTo(2L); + assertThat(reader.nextDouble()).isEqualTo(3.0); reader.endArray(); } @@ -48,9 +47,9 @@ public void testLenientNansAndInfinities() throws IOException { JsonTreeReader reader = new JsonTreeReader(element); reader.setLenient(true); reader.beginArray(); - assertTrue(Double.isNaN(reader.nextDouble())); - assertEquals(Double.NEGATIVE_INFINITY, reader.nextDouble(), 0); - assertEquals(Double.POSITIVE_INFINITY, reader.nextDouble(), 0); + assertThat(Double.isNaN(reader.nextDouble())).isTrue(); + assertThat(reader.nextDouble()).isEqualTo(Double.NEGATIVE_INFINITY); + assertThat(reader.nextDouble()).isEqualTo(Double.POSITIVE_INFINITY); reader.endArray(); } @@ -64,23 +63,23 @@ public void testStrictNansAndInfinities() throws IOException { reader.nextDouble(); fail(); } catch (MalformedJsonException e) { - assertEquals("JSON forbids NaN and infinities: NaN", e.getMessage()); + assertThat(e.getMessage()).isEqualTo("JSON forbids NaN and infinities: NaN"); } - assertEquals("NaN", reader.nextString()); + assertThat(reader.nextString()).isEqualTo("NaN"); try { reader.nextDouble(); fail(); } catch (MalformedJsonException e) { - assertEquals("JSON forbids NaN and infinities: -Infinity", e.getMessage()); + assertThat(e.getMessage()).isEqualTo("JSON forbids NaN and infinities: -Infinity"); } - assertEquals("-Infinity", reader.nextString()); + assertThat(reader.nextString()).isEqualTo("-Infinity"); try { reader.nextDouble(); fail(); } catch (MalformedJsonException e) { - assertEquals("JSON forbids NaN and infinities: Infinity", e.getMessage()); + assertThat(e.getMessage()).isEqualTo("JSON forbids NaN and infinities: Infinity"); } - assertEquals("Infinity", reader.nextString()); + assertThat(reader.nextString()).isEqualTo("Infinity"); reader.endArray(); } @@ -89,9 +88,9 @@ public void testNumbersFromStrings() throws IOException { JsonElement element = JsonParser.parseString("[\"1\", \"2\", \"3\"]"); JsonTreeReader reader = new JsonTreeReader(element); reader.beginArray(); - assertEquals(1, reader.nextInt()); - assertEquals(2L, reader.nextLong()); - assertEquals(3.0, reader.nextDouble(), 0); + assertThat(reader.nextInt()).isEqualTo(1); + assertThat(reader.nextLong()).isEqualTo(2L); + assertThat(reader.nextDouble()).isEqualTo(3.0); reader.endArray(); } @@ -100,7 +99,7 @@ public void testStringsFromNumbers() throws IOException { JsonElement element = JsonParser.parseString("[1]"); JsonTreeReader reader = new JsonTreeReader(element); reader.beginArray(); - assertEquals("1", reader.nextString()); + assertThat(reader.nextString()).isEqualTo("1"); reader.endArray(); } @@ -109,8 +108,8 @@ public void testBooleans() throws IOException { JsonElement element = JsonParser.parseString("[true, false]"); JsonTreeReader reader = new JsonTreeReader(element); reader.beginArray(); - assertEquals(true, reader.nextBoolean()); - assertEquals(false, reader.nextBoolean()); + assertThat(reader.nextBoolean()).isEqualTo(true); + assertThat(reader.nextBoolean()).isEqualTo(false); reader.endArray(); } @@ -129,8 +128,8 @@ public void testStrings() throws IOException { JsonElement element = JsonParser.parseString("[\"A\",\"B\"]"); JsonTreeReader reader = new JsonTreeReader(element); reader.beginArray(); - assertEquals("A", reader.nextString()); - assertEquals("B", reader.nextString()); + assertThat(reader.nextString()).isEqualTo("A"); + assertThat(reader.nextString()).isEqualTo("B"); reader.endArray(); } @@ -138,36 +137,36 @@ public void testStrings() throws IOException { public void testArray() throws IOException { JsonElement element = JsonParser.parseString("[1, 2, 3]"); JsonTreeReader reader = new JsonTreeReader(element); - assertEquals(JsonToken.BEGIN_ARRAY, reader.peek()); + assertThat(reader.peek()).isEqualTo(JsonToken.BEGIN_ARRAY); reader.beginArray(); - assertEquals(JsonToken.NUMBER, reader.peek()); - assertEquals(1, reader.nextInt()); - assertEquals(JsonToken.NUMBER, reader.peek()); - assertEquals(2, reader.nextInt()); - assertEquals(JsonToken.NUMBER, reader.peek()); - assertEquals(3, reader.nextInt()); - assertEquals(JsonToken.END_ARRAY, reader.peek()); + assertThat(reader.peek()).isEqualTo(JsonToken.NUMBER); + assertThat(reader.nextInt()).isEqualTo(1); + assertThat(reader.peek()).isEqualTo(JsonToken.NUMBER); + assertThat(reader.nextInt()).isEqualTo(2); + assertThat(reader.peek()).isEqualTo(JsonToken.NUMBER); + assertThat(reader.nextInt()).isEqualTo(3); + assertThat(reader.peek()).isEqualTo(JsonToken.END_ARRAY); reader.endArray(); - assertEquals(JsonToken.END_DOCUMENT, reader.peek()); + assertThat(reader.peek()).isEqualTo(JsonToken.END_DOCUMENT); } @Test public void testObject() throws IOException { JsonElement element = JsonParser.parseString("{\"A\": 1, \"B\": 2}"); JsonTreeReader reader = new JsonTreeReader(element); - assertEquals(JsonToken.BEGIN_OBJECT, reader.peek()); + assertThat(reader.peek()).isEqualTo(JsonToken.BEGIN_OBJECT); reader.beginObject(); - assertEquals(JsonToken.NAME, reader.peek()); - assertEquals("A", reader.nextName()); - assertEquals(JsonToken.NUMBER, reader.peek()); - assertEquals(1, reader.nextInt()); - assertEquals(JsonToken.NAME, reader.peek()); - assertEquals("B", reader.nextName()); - assertEquals(JsonToken.NUMBER, reader.peek()); - assertEquals(2, reader.nextInt()); - assertEquals(JsonToken.END_OBJECT, reader.peek()); + assertThat(reader.peek()).isEqualTo(JsonToken.NAME); + assertThat(reader.nextName()).isEqualTo("A"); + assertThat(reader.peek()).isEqualTo(JsonToken.NUMBER); + assertThat(reader.nextInt()).isEqualTo(1); + assertThat(reader.peek()).isEqualTo(JsonToken.NAME); + assertThat(reader.nextName()).isEqualTo("B"); + assertThat(reader.peek()).isEqualTo(JsonToken.NUMBER); + assertThat(reader.nextInt()).isEqualTo(2); + assertThat(reader.peek()).isEqualTo(JsonToken.END_OBJECT); reader.endObject(); - assertEquals(JsonToken.END_DOCUMENT, reader.peek()); + assertThat(reader.peek()).isEqualTo(JsonToken.END_DOCUMENT); } @Test @@ -197,12 +196,12 @@ public void testNestedObjects() throws IOException { JsonElement element = JsonParser.parseString("{\"A\":{},\"B\":{\"C\":{}}}"); JsonTreeReader reader = new JsonTreeReader(element); reader.beginObject(); - assertEquals("A", reader.nextName()); + assertThat(reader.nextName()).isEqualTo("A"); reader.beginObject(); reader.endObject(); - assertEquals("B", reader.nextName()); + assertThat(reader.nextName()).isEqualTo("B"); reader.beginObject(); - assertEquals("C", reader.nextName()); + assertThat(reader.nextName()).isEqualTo("C"); reader.beginObject(); reader.endObject(); reader.endObject(); @@ -222,11 +221,11 @@ public void testSkipValue() throws IOException { JsonElement element = JsonParser.parseString("[\"A\",{\"B\":[[]]},\"C\",[[]],\"D\",null]"); JsonTreeReader reader = new JsonTreeReader(element); reader.beginArray(); - assertEquals("A", reader.nextString()); + assertThat(reader.nextString()).isEqualTo("A"); reader.skipValue(); - assertEquals("C", reader.nextString()); + assertThat(reader.nextString()).isEqualTo("C"); reader.skipValue(); - assertEquals("D", reader.nextString()); + assertThat(reader.nextString()).isEqualTo("D"); reader.skipValue(); reader.endArray(); } @@ -319,7 +318,7 @@ public void testWrongType() throws IOException { fail(); } catch (IllegalStateException expected) { } - assertEquals("A", reader.nextString()); + assertThat(reader.nextString()).isEqualTo("A"); reader.endArray(); } @@ -334,7 +333,7 @@ public void testNextJsonElement() throws IOException { } catch (IllegalStateException expected) { } reader.nextName(); - assertEquals(reader.nextJsonElement(), new JsonPrimitive(1)); + assertThat(new JsonPrimitive(1)).isEqualTo(reader.nextJsonElement()); reader.nextName(); reader.beginObject(); try { diff --git a/gson/src/test/java/com/google/gson/internal/bind/JsonTreeReaderTest.java b/gson/src/test/java/com/google/gson/internal/bind/JsonTreeReaderTest.java index 0d17e7c57d..14ecbc9098 100644 --- a/gson/src/test/java/com/google/gson/internal/bind/JsonTreeReaderTest.java +++ b/gson/src/test/java/com/google/gson/internal/bind/JsonTreeReaderTest.java @@ -15,8 +15,7 @@ */ package com.google.gson.internal.bind; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; +import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.fail; import com.google.gson.JsonArray; @@ -39,8 +38,8 @@ public class JsonTreeReaderTest { public void testSkipValue_emptyJsonObject() throws IOException { JsonTreeReader in = new JsonTreeReader(new JsonObject()); in.skipValue(); - assertEquals(JsonToken.END_DOCUMENT, in.peek()); - assertEquals("$", in.getPath()); + assertThat(in.peek()).isEqualTo(JsonToken.END_DOCUMENT); + assertThat(in.getPath()).isEqualTo("$"); } @Test @@ -59,8 +58,8 @@ public void testSkipValue_filledJsonObject() throws IOException { jsonObject.addProperty("s", "text"); JsonTreeReader in = new JsonTreeReader(jsonObject); in.skipValue(); - assertEquals(JsonToken.END_DOCUMENT, in.peek()); - assertEquals("$", in.getPath()); + assertThat(in.peek()).isEqualTo(JsonToken.END_DOCUMENT); + assertThat(in.getPath()).isEqualTo("$"); } @Test @@ -70,9 +69,9 @@ public void testSkipValue_name() throws IOException { JsonTreeReader in = new JsonTreeReader(jsonObject); in.beginObject(); in.skipValue(); - assertEquals(JsonToken.STRING, in.peek()); - assertEquals("$.", in.getPath()); - assertEquals("value", in.nextString()); + assertThat(in.peek()).isEqualTo(JsonToken.STRING); + assertThat(in.getPath()).isEqualTo("$."); + assertThat(in.nextString()).isEqualTo("value"); } @Test @@ -80,12 +79,12 @@ public void testSkipValue_afterEndOfDocument() throws IOException { JsonTreeReader reader = new JsonTreeReader(new JsonObject()); reader.beginObject(); reader.endObject(); - assertEquals(JsonToken.END_DOCUMENT, reader.peek()); + assertThat(reader.peek()).isEqualTo(JsonToken.END_DOCUMENT); - assertEquals("$", reader.getPath()); + assertThat(reader.getPath()).isEqualTo("$"); reader.skipValue(); - assertEquals(JsonToken.END_DOCUMENT, reader.peek()); - assertEquals("$", reader.getPath()); + assertThat(reader.peek()).isEqualTo(JsonToken.END_DOCUMENT); + assertThat(reader.getPath()).isEqualTo("$"); } @Test @@ -93,8 +92,8 @@ public void testSkipValue_atArrayEnd() throws IOException { JsonTreeReader reader = new JsonTreeReader(new JsonArray()); reader.beginArray(); reader.skipValue(); - assertEquals(JsonToken.END_DOCUMENT, reader.peek()); - assertEquals("$", reader.getPath()); + assertThat(reader.peek()).isEqualTo(JsonToken.END_DOCUMENT); + assertThat(reader.getPath()).isEqualTo("$"); } @Test @@ -102,8 +101,8 @@ public void testSkipValue_atObjectEnd() throws IOException { JsonTreeReader reader = new JsonTreeReader(new JsonObject()); reader.beginObject(); reader.skipValue(); - assertEquals(JsonToken.END_DOCUMENT, reader.peek()); - assertEquals("$", reader.getPath()); + assertThat(reader.peek()).isEqualTo(JsonToken.END_DOCUMENT); + assertThat(reader.getPath()).isEqualTo("$"); } @Test @@ -111,7 +110,7 @@ public void testHasNext_endOfDocument() throws IOException { JsonTreeReader reader = new JsonTreeReader(new JsonObject()); reader.beginObject(); reader.endObject(); - assertFalse(reader.hasNext()); + assertThat(reader.hasNext()).isFalse(); } @Test @@ -134,8 +133,7 @@ public JsonElement deepCopy() { reader.peek(); fail(); } catch (MalformedJsonException expected) { - assertEquals("Custom JsonElement subclass " + CustomSubclass.class.getName() + " is not supported", - expected.getMessage()); + assertThat( expected.getMessage()).isEqualTo("Custom JsonElement subclass " + CustomSubclass.class.getName() + " is not supported"); } } diff --git a/gson/src/test/java/com/google/gson/internal/bind/JsonTreeWriterTest.java b/gson/src/test/java/com/google/gson/internal/bind/JsonTreeWriterTest.java index 4e2ed2409a..3801033a36 100644 --- a/gson/src/test/java/com/google/gson/internal/bind/JsonTreeWriterTest.java +++ b/gson/src/test/java/com/google/gson/internal/bind/JsonTreeWriterTest.java @@ -16,7 +16,7 @@ package com.google.gson.internal.bind; -import static org.junit.Assert.assertEquals; +import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.fail; import com.google.gson.JsonElement; @@ -39,7 +39,7 @@ public void testArray() throws IOException { writer.value(2); writer.value(3); writer.endArray(); - assertEquals("[1,2,3]", writer.get().toString()); + assertThat(writer.get().toString()).isEqualTo("[1,2,3]"); } @Test @@ -53,7 +53,7 @@ public void testNestedArray() throws IOException { writer.endArray(); writer.endArray(); writer.endArray(); - assertEquals("[[],[[]]]", writer.get().toString()); + assertThat(writer.get().toString()).isEqualTo("[[],[[]]]"); } @Test @@ -63,7 +63,7 @@ public void testObject() throws IOException { writer.name("A").value(1); writer.name("B").value(2); writer.endObject(); - assertEquals("{\"A\":1,\"B\":2}", writer.get().toString()); + assertThat(writer.get().toString()).isEqualTo("{\"A\":1,\"B\":2}"); } @Test @@ -80,7 +80,7 @@ public void testNestedObject() throws IOException { writer.beginObject(); writer.endObject(); writer.endObject(); - assertEquals("{\"A\":{\"B\":{}},\"C\":{}}", writer.get().toString()); + assertThat(writer.get().toString()).isEqualTo("{\"A\":{\"B\":{}},\"C\":{}}"); } @Test @@ -118,7 +118,7 @@ public void testSerializeNullsFalse() throws IOException { writer.name("A"); writer.nullValue(); writer.endObject(); - assertEquals("{}", writer.get().toString()); + assertThat(writer.get().toString()).isEqualTo("{}"); } @Test @@ -129,46 +129,46 @@ public void testSerializeNullsTrue() throws IOException { writer.name("A"); writer.nullValue(); writer.endObject(); - assertEquals("{\"A\":null}", writer.get().toString()); + assertThat(writer.get().toString()).isEqualTo("{\"A\":null}"); } @Test public void testEmptyWriter() { JsonTreeWriter writer = new JsonTreeWriter(); - assertEquals(JsonNull.INSTANCE, writer.get()); + assertThat(writer.get()).isEqualTo(JsonNull.INSTANCE); } @Test public void testBeginArray() throws Exception { JsonTreeWriter writer = new JsonTreeWriter(); - assertEquals(writer, writer.beginArray()); + assertThat(writer.beginArray()).isEqualTo(writer); } @Test public void testBeginObject() throws Exception { JsonTreeWriter writer = new JsonTreeWriter(); - assertEquals(writer, writer.beginObject()); + assertThat(writer.beginObject()).isEqualTo(writer); } @Test public void testValueString() throws Exception { JsonTreeWriter writer = new JsonTreeWriter(); String n = "as"; - assertEquals(writer, writer.value(n)); + assertThat(writer.value(n)).isEqualTo(writer); } @Test public void testBoolValue() throws Exception { JsonTreeWriter writer = new JsonTreeWriter(); boolean bool = true; - assertEquals(writer, writer.value(bool)); + assertThat(writer.value(bool)).isEqualTo(writer); } @Test public void testBoolMaisValue() throws Exception { JsonTreeWriter writer = new JsonTreeWriter(); Boolean bool = true; - assertEquals(writer, writer.value(bool)); + assertThat(writer.value(bool)).isEqualTo(writer); } @Test @@ -183,7 +183,7 @@ public void testLenientNansAndInfinities() throws IOException { writer.value(Double.NEGATIVE_INFINITY); writer.value(Double.POSITIVE_INFINITY); writer.endArray(); - assertEquals("[NaN,-Infinity,Infinity,NaN,-Infinity,Infinity]", writer.get().toString()); + assertThat(writer.get().toString()).isEqualTo("[NaN,-Infinity,Infinity,NaN,-Infinity,Infinity]"); } @Test diff --git a/gson/src/test/java/com/google/gson/internal/bind/RecursiveTypesResolveTest.java b/gson/src/test/java/com/google/gson/internal/bind/RecursiveTypesResolveTest.java index 9959360d85..5c0fe56cc8 100644 --- a/gson/src/test/java/com/google/gson/internal/bind/RecursiveTypesResolveTest.java +++ b/gson/src/test/java/com/google/gson/internal/bind/RecursiveTypesResolveTest.java @@ -16,8 +16,7 @@ package com.google.gson.internal.bind; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static com.google.common.truth.Truth.assertThat; import com.google.gson.Gson; import com.google.gson.TypeAdapter; @@ -51,7 +50,7 @@ private static class Foo2 { public void testRecursiveResolveSimple() { @SuppressWarnings("rawtypes") TypeAdapter adapter = new Gson().getAdapter(Foo1.class); - assertNotNull(adapter); + assertThat(adapter).isNotNull(); } /** @@ -60,26 +59,26 @@ public void testRecursiveResolveSimple() { @Test public void testDoubleSupertype() { - assertEquals($Gson$Types.supertypeOf(Number.class), - $Gson$Types.supertypeOf($Gson$Types.supertypeOf(Number.class))); + assertThat($Gson$Types.supertypeOf($Gson$Types.supertypeOf(Number.class))) + .isEqualTo($Gson$Types.supertypeOf(Number.class)); } @Test public void testDoubleSubtype() { - assertEquals($Gson$Types.subtypeOf(Number.class), - $Gson$Types.subtypeOf($Gson$Types.subtypeOf(Number.class))); + assertThat($Gson$Types.subtypeOf($Gson$Types.subtypeOf(Number.class))) + .isEqualTo($Gson$Types.subtypeOf(Number.class)); } @Test public void testSuperSubtype() { - assertEquals($Gson$Types.subtypeOf(Object.class), - $Gson$Types.supertypeOf($Gson$Types.subtypeOf(Number.class))); + assertThat($Gson$Types.supertypeOf($Gson$Types.subtypeOf(Number.class))) + .isEqualTo($Gson$Types.subtypeOf(Object.class)); } @Test public void testSubSupertype() { - assertEquals($Gson$Types.subtypeOf(Object.class), - $Gson$Types.subtypeOf($Gson$Types.supertypeOf(Number.class))); + assertThat($Gson$Types.subtypeOf($Gson$Types.supertypeOf(Number.class))) + .isEqualTo($Gson$Types.subtypeOf(Object.class)); } /** @@ -97,16 +96,16 @@ private static class TestType2 { } @Test - public void testRecursiveTypeVariablesResolve1() throws Exception { + public void testRecursiveTypeVariablesResolve1() { @SuppressWarnings("rawtypes") TypeAdapter adapter = new Gson().getAdapter(TestType.class); - assertNotNull(adapter); + assertThat(adapter).isNotNull(); } @Test - public void testRecursiveTypeVariablesResolve12() throws Exception { + public void testRecursiveTypeVariablesResolve12() { @SuppressWarnings("rawtypes") TypeAdapter adapter = new Gson().getAdapter(TestType2.class); - assertNotNull(adapter); + assertThat(adapter).isNotNull(); } } From cd1ccf4cc8e094309b0660cce376704b800b57f8 Mon Sep 17 00:00:00 2001 From: maicolAntali Date: Wed, 25 Jan 2023 15:26:56 +0100 Subject: [PATCH 09/14] Port Junit assert to Truth in `com.google.gson.internal.bind.util` --- .../internal/bind/util/ISO8601UtilsTest.java | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/gson/src/test/java/com/google/gson/internal/bind/util/ISO8601UtilsTest.java b/gson/src/test/java/com/google/gson/internal/bind/util/ISO8601UtilsTest.java index 4c162946fb..4db586531b 100644 --- a/gson/src/test/java/com/google/gson/internal/bind/util/ISO8601UtilsTest.java +++ b/gson/src/test/java/com/google/gson/internal/bind/util/ISO8601UtilsTest.java @@ -1,6 +1,6 @@ package com.google.gson.internal.bind.util; -import static org.junit.Assert.assertEquals; +import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.assertThrows; import static org.junit.Assert.fail; @@ -37,7 +37,7 @@ public void testDateFormatString() { Date date = calendar.getTime(); String dateStr = ISO8601Utils.format(date); String expectedDate = "2018-06-25"; - assertEquals(expectedDate, dateStr.substring(0, expectedDate.length())); + assertThat(dateStr.substring(0, expectedDate.length())).isEqualTo(expectedDate); } @Test @@ -46,7 +46,7 @@ public void testDateFormatWithMilliseconds() { Date date = new Date(time); String dateStr = ISO8601Utils.format(date, true); String expectedDate = "2018-06-28T18:06:16.870Z"; - assertEquals(expectedDate, dateStr); + assertThat(dateStr).isEqualTo(expectedDate); } @Test @@ -55,7 +55,7 @@ public void testDateFormatWithTimezone() { Date date = new Date(time); String dateStr = ISO8601Utils.format(date, true, TimeZone.getTimeZone("Brazil/East")); String expectedDate = "2018-06-28T15:06:16.870-03:00"; - assertEquals(expectedDate, dateStr); + assertThat(dateStr).isEqualTo(expectedDate); } @Test @@ -63,7 +63,7 @@ public void testDateParseWithDefaultTimezone() throws ParseException { String dateStr = "2018-06-25"; Date date = ISO8601Utils.parse(dateStr, new ParsePosition(0)); Date expectedDate = new GregorianCalendar(2018, Calendar.JUNE, 25).getTime(); - assertEquals(expectedDate, date); + assertThat(date).isEqualTo(expectedDate); } @Test @@ -93,7 +93,7 @@ public void testDateParseWithTimezone() throws ParseException { GregorianCalendar calendar = createUtcCalendar(); calendar.set(2018, Calendar.JUNE, 25, 3, 0); Date expectedDate = calendar.getTime(); - assertEquals(expectedDate, date); + assertThat(date).isEqualTo(expectedDate); } @Test @@ -103,11 +103,11 @@ public void testDateParseSpecialTimezone() throws ParseException { GregorianCalendar calendar = createUtcCalendar(); calendar.set(2018, Calendar.JUNE, 25, 3, 0); Date expectedDate = calendar.getTime(); - assertEquals(expectedDate, date); + assertThat(date).isEqualTo(expectedDate); } @Test - public void testDateParseInvalidTime() throws ParseException { + public void testDateParseInvalidTime() { final String dateStr = "2018-06-25T61:60:62-03:00"; assertThrows(ParseException.class, new ThrowingRunnable() { @Override From b3dbf618b5771527bfa64f470c649cd8335fcb33 Mon Sep 17 00:00:00 2001 From: maicolAntali Date: Sat, 28 Jan 2023 15:07:11 +0100 Subject: [PATCH 10/14] Port Junit assert to Truth in `com.google.gson.functional` --- .../com/google/gson/functional/ArrayTest.java | 104 +++-- .../functional/CircularReferenceTest.java | 24 +- .../gson/functional/CollectionTest.java | 149 ++++---- .../gson/functional/ConcurrencyTest.java | 6 +- .../functional/CustomDeserializerTest.java | 25 +- .../gson/functional/CustomSerializerTest.java | 13 +- .../functional/CustomTypeAdaptersTest.java | 73 ++-- .../functional/DefaultTypeAdaptersTest.java | 265 +++++++------ .../functional/DelegateTypeAdapterTest.java | 10 +- .../com/google/gson/functional/EnumTest.java | 89 +++-- .../functional/EnumWithObfuscatedTest.java | 6 +- .../google/gson/functional/EscapingTest.java | 33 +- .../ExclusionStrategyFunctionalTest.java | 65 ++-- .../gson/functional/ExposeFieldsTest.java | 43 +-- .../gson/functional/FieldExclusionTest.java | 18 +- .../gson/functional/FieldNamingTest.java | 50 +-- .../GsonVersionDiagnosticsTest.java | 12 +- .../gson/functional/InheritanceTest.java | 49 ++- .../gson/functional/InstanceCreatorTest.java | 28 +- .../google/gson/functional/InterfaceTest.java | 10 +- .../functional/InternationalizationTest.java | 26 +- .../gson/functional/Java17RecordTest.java | 123 +++--- .../JavaUtilConcurrentAtomicTest.java | 63 ++-- .../google/gson/functional/JavaUtilTest.java | 22 +- .../JsonAdapterAnnotationOnClassesTest.java | 34 +- .../JsonAdapterAnnotationOnFieldsTest.java | 48 ++- ...JsonAdapterSerializerDeserializerTest.java | 24 +- .../gson/functional/JsonParserTest.java | 18 +- .../google/gson/functional/JsonTreeTest.java | 16 +- .../google/gson/functional/LeniencyTest.java | 4 +- .../functional/MapAsArrayTypeAdapterTest.java | 29 +- .../com/google/gson/functional/MapTest.java | 230 ++++++----- .../MoreSpecificTypeSerializationTest.java | 34 +- .../gson/functional/NamingPolicyTest.java | 62 ++- .../functional/NullObjectAndFieldTest.java | 64 ++-- .../google/gson/functional/ObjectTest.java | 230 ++++++----- .../functional/ParameterizedTypesTest.java | 73 ++-- .../gson/functional/PrettyPrintingTest.java | 19 +- .../functional/PrimitiveCharacterTest.java | 14 +- .../google/gson/functional/PrimitiveTest.java | 357 +++++++++--------- .../gson/functional/PrintFormattingTest.java | 13 +- .../gson/functional/RawSerializationTest.java | 18 +- .../gson/functional/ReadersWritersTest.java | 35 +- .../ReflectionAccessFilterTest.java | 114 +++--- .../gson/functional/ReflectionAccessTest.java | 20 +- .../ReusedTypeVariablesFullyResolveTest.java | 14 +- ...ntimeTypeAdapterFactoryFunctionalTest.java | 12 +- .../google/gson/functional/SecurityTest.java | 15 +- .../gson/functional/SerializedNameTest.java | 14 +- .../functional/StreamingTypeAdaptersTest.java | 68 ++-- .../google/gson/functional/StringTest.java | 68 ++-- .../ToNumberPolicyFunctionalTest.java | 61 ++- .../gson/functional/TreeTypeAdaptersTest.java | 15 +- .../functional/TypeAdapterPrecedenceTest.java | 34 +- .../TypeAdapterRuntimeTypeWrapperTest.java | 16 +- .../functional/TypeHierarchyAdapterTest.java | 28 +- .../gson/functional/TypeVariableTest.java | 18 +- .../gson/functional/UncategorizedTest.java | 20 +- .../gson/functional/VersioningTest.java | 61 ++- .../internal/bind/JsonTreeReaderTest.java | 2 +- 60 files changed, 1543 insertions(+), 1665 deletions(-) diff --git a/gson/src/test/java/com/google/gson/functional/ArrayTest.java b/gson/src/test/java/com/google/gson/functional/ArrayTest.java index e1a8c02e74..b614f67ab4 100644 --- a/gson/src/test/java/com/google/gson/functional/ArrayTest.java +++ b/gson/src/test/java/com/google/gson/functional/ArrayTest.java @@ -16,10 +16,7 @@ package com.google.gson.functional; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.fail; import com.google.gson.Gson; @@ -51,14 +48,14 @@ public void setUp() throws Exception { @Test public void testTopLevelArrayOfIntsSerialization() { int[] target = {1, 2, 3, 4, 5, 6, 7, 8, 9}; - assertEquals("[1,2,3,4,5,6,7,8,9]", gson.toJson(target)); + assertThat(gson.toJson(target)).isEqualTo("[1,2,3,4,5,6,7,8,9]"); } @Test public void testTopLevelArrayOfIntsDeserialization() { int[] expected = {1, 2, 3, 4, 5, 6, 7, 8, 9}; int[] actual = gson.fromJson("[1,2,3,4,5,6,7,8,9]", int[].class); - assertArrayEquals(expected, actual); + assertThat(actual).isEqualTo(expected); } @Test @@ -74,19 +71,19 @@ public void testInvalidArrayDeserialization() { @Test public void testEmptyArraySerialization() { int[] target = {}; - assertEquals("[]", gson.toJson(target)); + assertThat(gson.toJson(target)).isEqualTo("[]"); } @Test public void testEmptyArrayDeserialization() { int[] actualObject = gson.fromJson("[]", int[].class); - assertTrue(actualObject.length == 0); + assertThat(actualObject.length == 0).isTrue(); Integer[] actualObject2 = gson.fromJson("[]", Integer[].class); - assertTrue(actualObject2.length == 0); + assertThat(actualObject2.length == 0).isTrue(); actualObject = gson.fromJson("[ ]", int[].class); - assertTrue(actualObject.length == 0); + assertThat(actualObject.length == 0).isTrue(); } @Test @@ -94,7 +91,7 @@ public void testNullsInArraySerialization() { String[] array = {"foo", null, "bar"}; String expected = "[\"foo\",null,\"bar\"]"; String json = gson.toJson(array); - assertEquals(expected, json); + assertThat(json).isEqualTo(expected); } @Test @@ -103,7 +100,7 @@ public void testNullsInArrayDeserialization() { String[] expected = {"foo", null, "bar"}; String[] target = gson.fromJson(json, expected.getClass()); for (int i = 0; i < expected.length; ++i) { - assertEquals(expected[i], target[i]); + assertThat(target[i]).isEqualTo(expected[i]); } } @@ -112,13 +109,13 @@ public void testSingleNullInArraySerialization() { BagOfPrimitives[] array = new BagOfPrimitives[1]; array[0] = null; String json = gson.toJson(array); - assertEquals("[null]", json); + assertThat(json).isEqualTo("[null]"); } @Test public void testSingleNullInArrayDeserialization() { BagOfPrimitives[] array = gson.fromJson("[null]", BagOfPrimitives[].class); - assertNull(array[0]); + assertThat(array[0]).isNull(); } @Test @@ -127,40 +124,40 @@ public void testNullsInArrayWithSerializeNullPropertySetSerialization() { String[] array = {"foo", null, "bar"}; String expected = "[\"foo\",null,\"bar\"]"; String json = gson.toJson(array); - assertEquals(expected, json); + assertThat(json).isEqualTo(expected); } @Test public void testArrayOfStringsSerialization() { String[] target = {"Hello", "World"}; - assertEquals("[\"Hello\",\"World\"]", gson.toJson(target)); + assertThat(gson.toJson(target)).isEqualTo("[\"Hello\",\"World\"]"); } @Test public void testArrayOfStringsDeserialization() { String json = "[\"Hello\",\"World\"]"; String[] target = gson.fromJson(json, String[].class); - assertEquals("Hello", target[0]); - assertEquals("World", target[1]); + assertThat(target[0]).isEqualTo("Hello"); + assertThat(target[1]).isEqualTo("World"); } @Test - public void testSingleStringArraySerialization() throws Exception { + public void testSingleStringArraySerialization() { String[] s = { "hello" }; String output = gson.toJson(s); - assertEquals("[\"hello\"]", output); + assertThat(output).isEqualTo("[\"hello\"]"); } @Test - public void testSingleStringArrayDeserialization() throws Exception { + public void testSingleStringArrayDeserialization() { String json = "[\"hello\"]"; String[] arrayType = gson.fromJson(json, String[].class); - assertEquals(1, arrayType.length); - assertEquals("hello", arrayType[0]); + assertThat(arrayType.length).isEqualTo(1); + assertThat(arrayType[0]).isEqualTo("hello"); } @Test - public void testArrayOfCollectionSerialization() throws Exception { + public void testArrayOfCollectionSerialization() { StringBuilder sb = new StringBuilder("["); int arraySize = 3; @@ -182,42 +179,42 @@ public void testArrayOfCollectionSerialization() throws Exception { sb.append(']'); String json = gson.toJson(arrayOfCollection, typeToSerialize); - assertEquals(sb.toString(), json); + assertThat(json).isEqualTo(sb.toString()); } @Test - public void testArrayOfCollectionDeserialization() throws Exception { + public void testArrayOfCollectionDeserialization() { String json = "[[1,2],[3,4]]"; Type type = new TypeToken[]>() {}.getType(); Collection[] target = gson.fromJson(json, type); - assertEquals(2, target.length); - assertArrayEquals(new Integer[] {1, 2}, target[0].toArray(new Integer[0])); - assertArrayEquals(new Integer[] {3, 4}, target[1].toArray(new Integer[0])); + assertThat(target.length).isEqualTo(2); + assertThat(target[0].toArray(new Integer[0])).isEqualTo(new Integer[] {1, 2}); + assertThat(target[1].toArray(new Integer[0])).isEqualTo(new Integer[] {3, 4}); } @Test - public void testArrayOfPrimitivesAsObjectsSerialization() throws Exception { + public void testArrayOfPrimitivesAsObjectsSerialization() { Object[] objs = new Object[] {1, "abc", 0.3f, 5L}; String json = gson.toJson(objs); - assertTrue(json.contains("abc")); - assertTrue(json.contains("0.3")); - assertTrue(json.contains("5")); + assertThat(json.contains("abc")).isTrue(); + assertThat(json.contains("0.3")).isTrue(); + assertThat(json.contains("5")).isTrue(); } @Test - public void testArrayOfPrimitivesAsObjectsDeserialization() throws Exception { + public void testArrayOfPrimitivesAsObjectsDeserialization() { String json = "[1,'abc',0.3,1.1,5]"; Object[] objs = gson.fromJson(json, Object[].class); - assertEquals(1, ((Number)objs[0]).intValue()); - assertEquals("abc", objs[1]); - assertEquals(0.3, ((Number)objs[2]).doubleValue(), 0); - assertEquals(new BigDecimal("1.1"), new BigDecimal(objs[3].toString())); - assertEquals(5, ((Number)objs[4]).shortValue()); + assertThat(((Number)objs[0]).intValue()).isEqualTo(1); + assertThat(objs[1]).isEqualTo("abc"); + assertThat(((Number)objs[2]).doubleValue()).isEqualTo(0.3); + assertThat(new BigDecimal(objs[3].toString())).isEqualTo(new BigDecimal("1.1")); + assertThat(((Number)objs[4]).shortValue()).isEqualTo(5); } @Test - public void testObjectArrayWithNonPrimitivesSerialization() throws Exception { + public void testObjectArrayWithNonPrimitivesSerialization() { ClassWithObjects classWithObjects = new ClassWithObjects(); BagOfPrimitives bagOfPrimitives = new BagOfPrimitives(); String classWithObjectsJson = gson.toJson(classWithObjects); @@ -226,21 +223,21 @@ public void testObjectArrayWithNonPrimitivesSerialization() throws Exception { Object[] objects = {classWithObjects, bagOfPrimitives}; String json = gson.toJson(objects); - assertTrue(json.contains(classWithObjectsJson)); - assertTrue(json.contains(bagOfPrimitivesJson)); + assertThat(json.contains(classWithObjectsJson)).isTrue(); + assertThat(json.contains(bagOfPrimitivesJson)).isTrue(); } @Test public void testArrayOfNullSerialization() { Object[] array = {null}; String json = gson.toJson(array); - assertEquals("[null]", json); + assertThat(json).isEqualTo("[null]"); } @Test public void testArrayOfNullDeserialization() { String[] values = gson.fromJson("[null]", String[].class); - assertNull(values[0]); + assertThat(values[0]).isNull(); } /** @@ -253,20 +250,20 @@ public void testMultidimensionalArraysSerialization() { {"Alcoa Inc", "29.01", "0.42", "1.47", "4/1 12:00am", "Manufacturing"} }; String json = gson.toJson(items); - assertTrue(json.contains("[[\"3m Co")); - assertTrue(json.contains("Manufacturing\"]]")); + assertThat(json.contains("[[\"3m Co")).isTrue(); + assertThat(json.contains("Manufacturing\"]]")).isTrue(); } @Test public void testMultidimensionalObjectArraysSerialization() { Object[][] array = {new Object[] { 1, 2 }}; - assertEquals("[[1,2]]", gson.toJson(array)); + assertThat(gson.toJson(array)).isEqualTo("[[1,2]]"); } @Test public void testMultidimensionalPrimitiveArraysSerialization() { int[][] array = {{1, 2}, {3, 4}}; - assertEquals("[[1,2],[3,4]]", gson.toJson(array)); + assertThat(gson.toJson(array)).isEqualTo("[[1,2],[3,4]]"); } /** @@ -275,7 +272,7 @@ public void testMultidimensionalPrimitiveArraysSerialization() { @Test public void testMixingTypesInObjectArraySerialization() { Object[] array = {1, 2, new Object[] {"one", "two", 3}}; - assertEquals("[1,2,[\"one\",\"two\",3]]", gson.toJson(array)); + assertThat(gson.toJson(array)).isEqualTo("[1,2,[\"one\",\"two\",3]]"); } /** @@ -286,15 +283,15 @@ public void testMultidimensionalArraysDeserialization() { String json = "[['3m Co','71.72','0.02','0.03','4/2 12:00am','Manufacturing']," + "['Alcoa Inc','29.01','0.42','1.47','4/1 12:00am','Manufacturing']]"; String[][] items = gson.fromJson(json, String[][].class); - assertEquals("3m Co", items[0][0]); - assertEquals("Manufacturing", items[1][5]); + assertThat(items[0][0]).isEqualTo("3m Co"); + assertThat(items[1][5]).isEqualTo("Manufacturing"); } @Test public void testMultidimensionalPrimitiveArraysDeserialization() { String json = "[[1,2],[3,4]]"; int[][] expected = {{1, 2}, {3, 4}}; - assertArrayEquals(expected, gson.fromJson(json, int[][].class)); + assertThat(gson.fromJson(json, int[][].class)).isEqualTo(expected); } /** http://code.google.com/p/google-gson/issues/detail?id=342 */ @@ -304,7 +301,6 @@ public void testArrayElementsAreArrays() { new String[] {"test1", "test2"}, new String[] {"test3", "test4"} }; - assertEquals("[[\"test1\",\"test2\"],[\"test3\",\"test4\"]]", - new Gson().toJson(stringArrays)); + assertThat(new Gson().toJson(stringArrays)).isEqualTo("[[\"test1\",\"test2\"],[\"test3\",\"test4\"]]"); } } diff --git a/gson/src/test/java/com/google/gson/functional/CircularReferenceTest.java b/gson/src/test/java/com/google/gson/functional/CircularReferenceTest.java index 053d8b46b4..582ec4d724 100644 --- a/gson/src/test/java/com/google/gson/functional/CircularReferenceTest.java +++ b/gson/src/test/java/com/google/gson/functional/CircularReferenceTest.java @@ -15,9 +15,7 @@ */ package com.google.gson.functional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; +import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.fail; import com.google.gson.Gson; @@ -48,7 +46,7 @@ public void setUp() throws Exception { } @Test - public void testCircularSerialization() throws Exception { + public void testCircularSerialization() { ContainsReferenceToSelfType a = new ContainsReferenceToSelfType(); ContainsReferenceToSelfType b = new ContainsReferenceToSelfType(); a.children.add(b); @@ -61,16 +59,16 @@ public void testCircularSerialization() throws Exception { } @Test - public void testSelfReferenceIgnoredInSerialization() throws Exception { + public void testSelfReferenceIgnoredInSerialization() { ClassOverridingEquals objA = new ClassOverridingEquals(); objA.ref = objA; String json = gson.toJson(objA); - assertFalse(json.contains("ref")); // self-reference is ignored + assertThat(json.contains("ref")).isFalse(); // self-reference is ignored } @Test - public void testSelfReferenceArrayFieldSerialization() throws Exception { + public void testSelfReferenceArrayFieldSerialization() { ClassWithSelfReferenceArray objA = new ClassWithSelfReferenceArray(); objA.children = new ClassWithSelfReferenceArray[]{objA}; @@ -82,7 +80,7 @@ public void testSelfReferenceArrayFieldSerialization() throws Exception { } @Test - public void testSelfReferenceCustomHandlerSerialization() throws Exception { + public void testSelfReferenceCustomHandlerSerialization() { ClassWithSelfReference obj = new ClassWithSelfReference(); obj.child = obj; Gson gson = new GsonBuilder().registerTypeAdapter(ClassWithSelfReference.class, new JsonSerializer() { @@ -102,22 +100,22 @@ public void testSelfReferenceCustomHandlerSerialization() throws Exception { } @Test - public void testDirectedAcyclicGraphSerialization() throws Exception { + public void testDirectedAcyclicGraphSerialization() { ContainsReferenceToSelfType a = new ContainsReferenceToSelfType(); ContainsReferenceToSelfType b = new ContainsReferenceToSelfType(); ContainsReferenceToSelfType c = new ContainsReferenceToSelfType(); a.children.add(b); a.children.add(c); b.children.add(c); - assertNotNull(gson.toJson(a)); + assertThat(gson.toJson(a)).isNotNull(); } @Test - public void testDirectedAcyclicGraphDeserialization() throws Exception { + public void testDirectedAcyclicGraphDeserialization() { String json = "{\"children\":[{\"children\":[{\"children\":[]}]},{\"children\":[]}]}"; ContainsReferenceToSelfType target = gson.fromJson(json, ContainsReferenceToSelfType.class); - assertNotNull(target); - assertEquals(2, target.children.size()); + assertThat(target).isNotNull(); + assertThat(target.children).hasSize(2); } private static class ContainsReferenceToSelfType { diff --git a/gson/src/test/java/com/google/gson/functional/CollectionTest.java b/gson/src/test/java/com/google/gson/functional/CollectionTest.java index e40afe24d0..3d444c7fbb 100644 --- a/gson/src/test/java/com/google/gson/functional/CollectionTest.java +++ b/gson/src/test/java/com/google/gson/functional/CollectionTest.java @@ -16,10 +16,7 @@ package com.google.gson.functional; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static com.google.common.truth.Truth.assertThat; import com.google.gson.Gson; import com.google.gson.GsonBuilder; @@ -65,7 +62,7 @@ public void testTopLevelCollectionOfIntegersSerialization() { Collection target = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9); Type targetType = new TypeToken>() {}.getType(); String json = gson.toJson(target, targetType); - assertEquals("[1,2,3,4,5,6,7,8,9]", json); + assertThat(json).isEqualTo("[1,2,3,4,5,6,7,8,9]"); } @Test @@ -74,11 +71,11 @@ public void testTopLevelCollectionOfIntegersDeserialization() { Type collectionType = new TypeToken>() { }.getType(); Collection target = gson.fromJson(json, collectionType); int[] expected = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; - assertArrayEquals(expected, toIntArray(target)); + assertThat(toIntArray(target)).isEqualTo(expected); } @Test - public void testTopLevelListOfIntegerCollectionsDeserialization() throws Exception { + public void testTopLevelListOfIntegerCollectionsDeserialization() { String json = "[[1,2,3],[4,5,6],[7,8,9]]"; Type collectionType = new TypeToken>>() {}.getType(); List> target = gson.fromJson(json, collectionType); @@ -91,7 +88,7 @@ public void testTopLevelListOfIntegerCollectionsDeserialization() throws Excepti } for (int i = 0; i < 3; i++) { - assertArrayEquals(expected[i], toIntArray(target.get(i))); + assertThat(toIntArray(target.get(i))).isEqualTo(expected[i]); } } @@ -102,8 +99,8 @@ public void testLinkedListSerialization() { list.add("a2"); Type linkedListType = new TypeToken>() {}.getType(); String json = gson.toJson(list, linkedListType); - assertTrue(json.contains("a1")); - assertTrue(json.contains("a2")); + assertThat(json.contains("a1")).isTrue(); + assertThat(json.contains("a2")).isTrue(); } @Test @@ -111,8 +108,8 @@ public void testLinkedListDeserialization() { String json = "['a1','a2']"; Type linkedListType = new TypeToken>() {}.getType(); List list = gson.fromJson(json, linkedListType); - assertEquals("a1", list.get(0)); - assertEquals("a2", list.get(1)); + assertThat(list.get(0)).isEqualTo("a1"); + assertThat(list.get(1)).isEqualTo("a2"); } @Test @@ -122,8 +119,8 @@ public void testQueueSerialization() { queue.add("a2"); Type queueType = new TypeToken>() {}.getType(); String json = gson.toJson(queue, queueType); - assertTrue(json.contains("a1")); - assertTrue(json.contains("a2")); + assertThat(json.contains("a1")).isTrue(); + assertThat(json.contains("a2")).isTrue(); } @Test @@ -131,45 +128,45 @@ public void testQueueDeserialization() { String json = "['a1','a2']"; Type queueType = new TypeToken>() {}.getType(); Queue queue = gson.fromJson(json, queueType); - assertEquals("a1", queue.element()); + assertThat(queue.element()).isEqualTo("a1"); queue.remove(); - assertEquals("a2", queue.element()); + assertThat(queue.element()).isEqualTo("a2"); } @Test - public void testPriorityQueue() throws Exception { + public void testPriorityQueue() { Type type = new TypeToken>(){}.getType(); PriorityQueue queue = gson.fromJson("[10, 20, 22]", type); - assertEquals(3, queue.size()); + assertThat(queue.size()).isEqualTo(3); String json = gson.toJson(queue); - assertEquals(10, queue.remove().intValue()); - assertEquals(20, queue.remove().intValue()); - assertEquals(22, queue.remove().intValue()); - assertEquals("[10,20,22]", json); + assertThat(queue.remove()).isEqualTo(10); + assertThat(queue.remove()).isEqualTo(20); + assertThat(queue.remove()).isEqualTo(22); + assertThat(json).isEqualTo("[10,20,22]"); } @Test public void testVector() { Type type = new TypeToken>(){}.getType(); Vector target = gson.fromJson("[10, 20, 31]", type); - assertEquals(3, target.size()); - assertEquals(10, target.get(0).intValue()); - assertEquals(20, target.get(1).intValue()); - assertEquals(31, target.get(2).intValue()); + assertThat(target.size()).isEqualTo(3); + assertThat(target.get(0)).isEqualTo(10); + assertThat(target.get(1)).isEqualTo(20); + assertThat(target.get(2)).isEqualTo(31); String json = gson.toJson(target); - assertEquals("[10,20,31]", json); + assertThat(json).isEqualTo("[10,20,31]"); } @Test public void testStack() { Type type = new TypeToken>(){}.getType(); Stack target = gson.fromJson("[11, 13, 17]", type); - assertEquals(3, target.size()); + assertThat(target.size()).isEqualTo(3); String json = gson.toJson(target); - assertEquals(17, target.pop().intValue()); - assertEquals(13, target.pop().intValue()); - assertEquals(11, target.pop().intValue()); - assertEquals("[11,13,17]", json); + assertThat(target.pop()).isEqualTo(17); + assertThat(target.pop()).isEqualTo(13); + assertThat(target.pop()).isEqualTo(11); + assertThat(json).isEqualTo("[11,13,17]"); } @Test @@ -181,7 +178,7 @@ public void testNullsInListSerialization() { String expected = "[\"foo\",null,\"bar\"]"; Type typeOfList = new TypeToken>() {}.getType(); String json = gson.toJson(list, typeOfList); - assertEquals(expected, json); + assertThat(json).isEqualTo(expected); } @Test @@ -194,7 +191,7 @@ public void testNullsInListDeserialization() { Type expectedType = new TypeToken>() {}.getType(); List target = gson.fromJson(json, expectedType); for (int i = 0; i < expected.size(); ++i) { - assertEquals(expected.get(i), target.get(i)); + assertThat(target.get(i)).isEqualTo(expected.get(i)); } } @@ -203,10 +200,10 @@ public void testCollectionOfObjectSerialization() { List target = new ArrayList<>(); target.add("Hello"); target.add("World"); - assertEquals("[\"Hello\",\"World\"]", gson.toJson(target)); + assertThat(gson.toJson(target)).isEqualTo("[\"Hello\",\"World\"]"); Type type = new TypeToken>() {}.getType(); - assertEquals("[\"Hello\",\"World\"]", gson.toJson(target, type)); + assertThat(gson.toJson(target, type)).isEqualTo("[\"Hello\",\"World\"]"); } @Test @@ -215,10 +212,10 @@ public void testCollectionOfObjectWithNullSerialization() { target.add("Hello"); target.add(null); target.add("World"); - assertEquals("[\"Hello\",null,\"World\"]", gson.toJson(target)); + assertThat(gson.toJson(target)).isEqualTo("[\"Hello\",null,\"World\"]"); Type type = new TypeToken>() {}.getType(); - assertEquals("[\"Hello\",null,\"World\"]", gson.toJson(target, type)); + assertThat(gson.toJson(target, type)).isEqualTo("[\"Hello\",null,\"World\"]"); } @Test @@ -226,7 +223,7 @@ public void testCollectionOfStringsSerialization() { List target = new ArrayList<>(); target.add("Hello"); target.add("World"); - assertEquals("[\"Hello\",\"World\"]", gson.toJson(target)); + assertThat(gson.toJson(target)).isEqualTo("[\"Hello\",\"World\"]"); } @Test @@ -238,10 +235,10 @@ public void testCollectionOfBagOfPrimitivesSerialization() { target.add(objB); String result = gson.toJson(target); - assertTrue(result.startsWith("[")); - assertTrue(result.endsWith("]")); + assertThat(result.startsWith("[")).isTrue(); + assertThat(result.endsWith("]")).isTrue(); for (BagOfPrimitives obj : target) { - assertTrue(result.contains(obj.getExpectedJson())); + assertThat(result.contains(obj.getExpectedJson())).isTrue(); } } @@ -251,14 +248,14 @@ public void testCollectionOfStringsDeserialization() { Type collectionType = new TypeToken>() { }.getType(); Collection target = gson.fromJson(json, collectionType); - assertTrue(target.contains("Hello")); - assertTrue(target.contains("World")); + assertThat(target.contains("Hello")).isTrue(); + assertThat(target.contains("World")).isTrue(); } @Test public void testRawCollectionOfIntegersSerialization() { Collection target = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9); - assertEquals("[1,2,3,4,5,6,7,8,9]", gson.toJson(target)); + assertThat(gson.toJson(target)).isEqualTo("[1,2,3,4,5,6,7,8,9]"); } @Test @@ -266,7 +263,7 @@ public void testObjectCollectionSerialization() { BagOfPrimitives bag1 = new BagOfPrimitives(); Collection target = Arrays.asList(bag1, bag1, "test"); String json = gson.toJson(target); - assertTrue(json.contains(bag1.getExpectedJson())); + assertThat(json.contains(bag1.getExpectedJson())).isTrue(); } @Test @@ -274,12 +271,12 @@ public void testRawCollectionDeserializationNotAlllowed() { String json = "[0,1,2,3,4,5,6,7,8,9]"; Collection integers = gson.fromJson(json, Collection.class); // JsonReader converts numbers to double by default so we need a floating point comparison - assertEquals(Arrays.asList(0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0), integers); + assertThat(integers).isEqualTo(Arrays.asList(0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0)); json = "[\"Hello\", \"World\"]"; Collection strings = gson.fromJson(json, Collection.class); - assertTrue(strings.contains("Hello")); - assertTrue(strings.contains("World")); + assertThat(strings.contains("Hello")).isTrue(); + assertThat(strings.contains("World")).isTrue(); } @Test @@ -287,40 +284,40 @@ public void testRawCollectionOfBagOfPrimitivesNotAllowed() { BagOfPrimitives bag = new BagOfPrimitives(10, 20, false, "stringValue"); String json = '[' + bag.getExpectedJson() + ',' + bag.getExpectedJson() + ']'; Collection target = gson.fromJson(json, Collection.class); - assertEquals(2, target.size()); + assertThat(target.size()).isEqualTo(2); for (Object bag1 : target) { // Gson 2.0 converts raw objects into maps @SuppressWarnings("unchecked") Map values = (Map) bag1; - assertTrue(values.containsValue(10.0)); - assertTrue(values.containsValue(20.0)); - assertTrue(values.containsValue("stringValue")); + assertThat(values.containsValue(10.0)).isTrue(); + assertThat(values.containsValue(20.0)).isTrue(); + assertThat(values.containsValue("stringValue")).isTrue(); } } @Test - public void testWildcardPrimitiveCollectionSerilaization() throws Exception { + public void testWildcardPrimitiveCollectionSerilaization() { Collection target = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9); Type collectionType = new TypeToken>() { }.getType(); String json = gson.toJson(target, collectionType); - assertEquals("[1,2,3,4,5,6,7,8,9]", json); + assertThat(json).isEqualTo("[1,2,3,4,5,6,7,8,9]"); json = gson.toJson(target); - assertEquals("[1,2,3,4,5,6,7,8,9]", json); + assertThat(json).isEqualTo("[1,2,3,4,5,6,7,8,9]"); } @Test - public void testWildcardPrimitiveCollectionDeserilaization() throws Exception { + public void testWildcardPrimitiveCollectionDeserilaization() { String json = "[1,2,3,4,5,6,7,8,9]"; Type collectionType = new TypeToken>() { }.getType(); Collection target = gson.fromJson(json, collectionType); - assertEquals(9, target.size()); - assertTrue(target.contains(1)); - assertTrue(target.contains(9)); + assertThat(target.size()).isEqualTo(9); + assertThat(target.contains(1)).isTrue(); + assertThat(target.contains(9)).isTrue(); } @Test - public void testWildcardCollectionField() throws Exception { + public void testWildcardCollectionField() { Collection collection = new ArrayList<>(); BagOfPrimitives objA = new BagOfPrimitives(3L, 1, true, "blah"); BagOfPrimitives objB = new BagOfPrimitives(2L, 6, false, "blahB"); @@ -329,14 +326,14 @@ public void testWildcardCollectionField() throws Exception { ObjectWithWildcardCollection target = new ObjectWithWildcardCollection(collection); String json = gson.toJson(target); - assertTrue(json.contains(objA.getExpectedJson())); - assertTrue(json.contains(objB.getExpectedJson())); + assertThat(json.contains(objA.getExpectedJson())).isTrue(); + assertThat(json.contains(objB.getExpectedJson())).isTrue(); target = gson.fromJson(json, ObjectWithWildcardCollection.class); Collection deserializedCollection = target.getCollection(); - assertEquals(2, deserializedCollection.size()); - assertTrue(deserializedCollection.contains(objA)); - assertTrue(deserializedCollection.contains(objB)); + assertThat(deserializedCollection.size()).isEqualTo(2); + assertThat(deserializedCollection.contains(objA)).isTrue(); + assertThat(deserializedCollection.contains(objB)).isTrue(); } @Test @@ -345,9 +342,9 @@ public void testFieldIsArrayList() { object.longs.add(1L); object.longs.add(3L); String json = gson.toJson(object, HasArrayListField.class); - assertEquals("{\"longs\":[1,3]}", json); + assertThat(json).isEqualTo("{\"longs\":[1,3]}"); HasArrayListField copy = gson.fromJson("{\"longs\":[1,3]}", HasArrayListField.class); - assertEquals(Arrays.asList(1L, 3L), copy.longs); + assertThat(copy.longs).isEqualTo(Arrays.asList(1L, 3L)); } @Test @@ -362,7 +359,7 @@ public void testUserCollectionTypeAdapter() { Gson gson = new GsonBuilder() .registerTypeAdapter(listOfString, stringListSerializer) .create(); - assertEquals("\"ab;cd\"", gson.toJson(Arrays.asList("ab", "cd"), listOfString)); + assertThat(gson.toJson(Arrays.asList("ab", "cd"), listOfString)).isEqualTo("\"ab;cd\""); } static class HasArrayListField { @@ -375,7 +372,7 @@ private static int[] toIntArray(Collection collection) { for (Iterator iterator = collection.iterator(); iterator.hasNext(); ++i) { Object obj = iterator.next(); if (obj instanceof Integer) { - ints[i] = ((Integer)obj).intValue(); + ints[i] = (Integer) obj; } else if (obj instanceof Long) { ints[i] = ((Long)obj).intValue(); } @@ -407,17 +404,17 @@ public void testSetSerialization() { set.add(new Entry(1)); set.add(new Entry(2)); String json = gson.toJson(set); - assertTrue(json.contains("1")); - assertTrue(json.contains("2")); + assertThat(json.contains("1")).isTrue(); + assertThat(json.contains("2")).isTrue(); } @Test public void testSetDeserialization() { String json = "[{value:1},{value:2}]"; Type type = new TypeToken>() {}.getType(); Set set = gson.fromJson(json, type); - assertEquals(2, set.size()); + assertThat(set.size()).isEqualTo(2); for (Entry entry : set) { - assertTrue(entry.value == 1 || entry.value == 2); + assertThat(entry.value == 1 || entry.value == 2).isTrue(); } } @@ -436,8 +433,8 @@ public void testIssue1107() { "}"; BigClass bigClass = new Gson().fromJson(json, BigClass.class); SmallClass small = bigClass.inBig.get("key").get(0); - assertNotNull(small); - assertEquals("hello", small.inSmall); + assertThat(small).isNotNull(); + assertThat(small.inSmall).isEqualTo("hello"); } } diff --git a/gson/src/test/java/com/google/gson/functional/ConcurrencyTest.java b/gson/src/test/java/com/google/gson/functional/ConcurrencyTest.java index eeabcee165..151961d0da 100644 --- a/gson/src/test/java/com/google/gson/functional/ConcurrencyTest.java +++ b/gson/src/test/java/com/google/gson/functional/ConcurrencyTest.java @@ -15,7 +15,7 @@ */ package com.google.gson.functional; -import static org.junit.Assert.assertFalse; +import static com.google.common.truth.Truth.assertThat; import com.google.gson.Gson; import java.util.concurrent.CountDownLatch; @@ -91,7 +91,7 @@ public void testMultiThreadSerialization() throws InterruptedException { } startLatch.countDown(); finishedLatch.await(); - assertFalse(failed.get()); + assertThat(failed.get()).isFalse(); } /** @@ -122,7 +122,7 @@ public void testMultiThreadDeserialization() throws InterruptedException { } startLatch.countDown(); finishedLatch.await(); - assertFalse(failed.get()); + assertThat(failed.get()).isFalse(); } @SuppressWarnings("unused") diff --git a/gson/src/test/java/com/google/gson/functional/CustomDeserializerTest.java b/gson/src/test/java/com/google/gson/functional/CustomDeserializerTest.java index d5b0728547..0ee5d8605d 100644 --- a/gson/src/test/java/com/google/gson/functional/CustomDeserializerTest.java +++ b/gson/src/test/java/com/google/gson/functional/CustomDeserializerTest.java @@ -16,8 +16,7 @@ package com.google.gson.functional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static com.google.common.truth.Truth.assertThat; import com.google.gson.Gson; import com.google.gson.GsonBuilder; @@ -50,21 +49,21 @@ public void setUp() throws Exception { } @Test - public void testDefaultConstructorNotCalledOnObject() throws Exception { + public void testDefaultConstructorNotCalledOnObject() { DataHolder data = new DataHolder(DEFAULT_VALUE); String json = gson.toJson(data); DataHolder actual = gson.fromJson(json, DataHolder.class); - assertEquals(DEFAULT_VALUE + SUFFIX, actual.getData()); + assertThat(actual.getData()).isEqualTo(DEFAULT_VALUE + SUFFIX); } @Test - public void testDefaultConstructorNotCalledOnField() throws Exception { + public void testDefaultConstructorNotCalledOnField() { DataHolderWrapper dataWrapper = new DataHolderWrapper(new DataHolder(DEFAULT_VALUE)); String json = gson.toJson(dataWrapper); DataHolderWrapper actual = gson.fromJson(json, DataHolderWrapper.class); - assertEquals(DEFAULT_VALUE + SUFFIX, actual.getWrappedData().getData()); + assertThat(actual.getWrappedData().getData()).isEqualTo(DEFAULT_VALUE + SUFFIX); } private static class DataHolder { @@ -124,7 +123,7 @@ public void testJsonTypeFieldBasedDeserialization() { } }).create(); SubType1 target = (SubType1) gson.fromJson(json, MyBase.class); - assertEquals("abc", target.field1); + assertThat(target.field1).isEqualTo("abc"); } private static class MyBase { @@ -164,7 +163,7 @@ public Base deserialize(JsonElement json, Type typeOfT, JsonDeserializationConte }).create(); String json = "{baseName:'Base',subName:'SubRevised'}"; Base target = gson.fromJson(json, Base.class); - assertNull(target); + assertThat(target).isNull(); } @Test @@ -179,7 +178,7 @@ public Base deserialize(JsonElement json, Type typeOfT, JsonDeserializationConte }).create(); String json = "{base:{baseName:'Base',subName:'SubRevised'}}"; ClassWithBaseField target = gson.fromJson(json, ClassWithBaseField.class); - assertNull(target.base); + assertThat(target.base).isNull(); } @Test @@ -194,8 +193,8 @@ public Base deserialize(JsonElement json, Type typeOfT, JsonDeserializationConte }).create(); String json = "[{baseName:'Base'},{baseName:'Base'}]"; Base[] target = gson.fromJson(json, Base[].class); - assertNull(target[0]); - assertNull(target[1]); + assertThat(target[0]).isNull(); + assertThat(target[1]).isNull(); } @Test @@ -210,8 +209,8 @@ public Base deserialize(JsonElement json, Type typeOfT, JsonDeserializationConte }).create(); String json = "{bases:[{baseName:'Base'},{baseName:'Base'}]}"; ClassWithBaseArray target = gson.fromJson(json, ClassWithBaseArray.class); - assertNull(target.bases[0]); - assertNull(target.bases[1]); + assertThat(target.bases[0]).isNull(); + assertThat(target.bases[1]).isNull(); } private static final class ClassWithBaseArray { diff --git a/gson/src/test/java/com/google/gson/functional/CustomSerializerTest.java b/gson/src/test/java/com/google/gson/functional/CustomSerializerTest.java index 3e450ac90b..ce54b8d2b8 100644 --- a/gson/src/test/java/com/google/gson/functional/CustomSerializerTest.java +++ b/gson/src/test/java/com/google/gson/functional/CustomSerializerTest.java @@ -16,8 +16,7 @@ package com.google.gson.functional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static com.google.common.truth.Truth.assertThat; import com.google.gson.Gson; import com.google.gson.GsonBuilder; @@ -52,7 +51,7 @@ public void testBaseClassSerializerInvokedForBaseClassFields() { ClassWithBaseField target = new ClassWithBaseField(new Base()); JsonObject json = (JsonObject) gson.toJsonTree(target); JsonObject base = json.get("base").getAsJsonObject(); - assertEquals(BaseSerializer.NAME, base.get(Base.SERIALIZER_KEY).getAsString()); + assertThat(base.get(Base.SERIALIZER_KEY).getAsString()).isEqualTo(BaseSerializer.NAME); } @Test @@ -64,7 +63,7 @@ public void testSubClassSerializerInvokedForBaseClassFieldsHoldingSubClassInstan ClassWithBaseField target = new ClassWithBaseField(new Sub()); JsonObject json = (JsonObject) gson.toJsonTree(target); JsonObject base = json.get("base").getAsJsonObject(); - assertEquals(SubSerializer.NAME, base.get(Base.SERIALIZER_KEY).getAsString()); + assertThat(base.get(Base.SERIALIZER_KEY).getAsString()).isEqualTo(SubSerializer.NAME); } @Test @@ -78,7 +77,7 @@ public void testSubClassSerializerInvokedForBaseClassFieldsHoldingArrayOfSubClas JsonArray array = json.get("base").getAsJsonArray(); for (JsonElement element : array) { JsonElement serializerKey = element.getAsJsonObject().get(Base.SERIALIZER_KEY); - assertEquals(SubSerializer.NAME, serializerKey.getAsString()); + assertThat(serializerKey.getAsString()).isEqualTo(SubSerializer.NAME); } } @@ -90,7 +89,7 @@ public void testBaseClassSerializerInvokedForBaseClassFieldsHoldingSubClassInsta ClassWithBaseField target = new ClassWithBaseField(new Sub()); JsonObject json = (JsonObject) gson.toJsonTree(target); JsonObject base = json.get("base").getAsJsonObject(); - assertEquals(BaseSerializer.NAME, base.get(Base.SERIALIZER_KEY).getAsString()); + assertThat(base.get(Base.SERIALIZER_KEY).getAsString()).isEqualTo(BaseSerializer.NAME); } @Test @@ -103,6 +102,6 @@ public void testSerializerReturnsNull() { }) .create(); JsonElement json = gson.toJsonTree(new Base()); - assertTrue(json.isJsonNull()); + assertThat(json.isJsonNull()).isTrue(); } } diff --git a/gson/src/test/java/com/google/gson/functional/CustomTypeAdaptersTest.java b/gson/src/test/java/com/google/gson/functional/CustomTypeAdaptersTest.java index 3881f09685..cfcf166bd1 100644 --- a/gson/src/test/java/com/google/gson/functional/CustomTypeAdaptersTest.java +++ b/gson/src/test/java/com/google/gson/functional/CustomTypeAdaptersTest.java @@ -15,10 +15,7 @@ */ package com.google.gson.functional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static com.google.common.truth.Truth.assertThat; import com.google.gson.Gson; import com.google.gson.GsonBuilder; @@ -71,7 +68,7 @@ public void testCustomSerializers() { } }).create(); ClassWithCustomTypeConverter target = new ClassWithCustomTypeConverter(); - assertEquals("{\"bag\":5,\"value\":25}", gson.toJson(target)); + assertThat(gson.toJson(target)).isEqualTo("{\"bag\":5,\"value\":25}"); } @Test @@ -88,7 +85,7 @@ public void testCustomDeserializers() { }).create(); String json = "{\"bag\":5,\"value\":25}"; ClassWithCustomTypeConverter target = gson.fromJson(json, ClassWithCustomTypeConverter.class); - assertEquals(5, target.getBag().getIntValue()); + assertThat(target.getBag().getIntValue()).isEqualTo(5); } @Test @@ -100,7 +97,7 @@ public void disable_testCustomSerializersOfSelf() { String jsonFromCustomSerializer = gson.toJson(newFooObject); String jsonFromGson = basicGson.toJson(newFooObject); - assertEquals(jsonFromGson, jsonFromCustomSerializer); + assertThat(jsonFromCustomSerializer).isEqualTo(jsonFromGson); } @Test @@ -112,8 +109,8 @@ public void disable_testCustomDeserializersOfSelf() { String json = basicGson.toJson(expectedFoo); Foo newFooObject = gson.fromJson(json, Foo.class); - assertEquals(expectedFoo.key, newFooObject.key); - assertEquals(expectedFoo.value, newFooObject.value); + assertThat(newFooObject.key).isEqualTo(expectedFoo.key); + assertThat(newFooObject.value).isEqualTo(expectedFoo.value); } @Test @@ -126,7 +123,7 @@ public void testCustomNestedSerializers() { } }).create(); ClassWithCustomTypeConverter target = new ClassWithCustomTypeConverter(); - assertEquals("{\"bag\":6,\"value\":10}", gson.toJson(target)); + assertThat(gson.toJson(target)).isEqualTo("{\"bag\":6,\"value\":10}"); } @Test @@ -141,7 +138,7 @@ public void testCustomNestedDeserializers() { }).create(); String json = "{\"bag\":7,\"value\":25}"; ClassWithCustomTypeConverter target = gson.fromJson(json, ClassWithCustomTypeConverter.class); - assertEquals(7, target.getBag().getIntValue()); + assertThat(target.getBag().getIntValue()).isEqualTo(7); } @Test @@ -156,10 +153,10 @@ public JsonElement serialize(Base src, Type typeOfSrc, JsonSerializationContext }).create(); Base b = new Base(); String json = gson.toJson(b); - assertTrue(json.contains("value")); + assertThat(json).contains("value"); b = new Derived(); json = gson.toJson(b); - assertTrue(json.contains("derivedValue")); + assertThat(json).contains("derivedValue"); } @Test @@ -174,11 +171,11 @@ public JsonElement serialize(Base src, Type typeOfSrc, JsonSerializationContext }).create(); Base b = new Base(); String json = gson.toJson(b); - assertTrue(json.contains("value")); + assertThat(json.contains("value")).isTrue(); b = new Derived(); json = gson.toJson(b, Base.class); - assertTrue(json.contains("value")); - assertFalse(json.contains("derivedValue")); + assertThat(json.contains("value")).isTrue(); + assertThat(json.contains("derivedValue")).isFalse(); } private static class Base { @@ -231,8 +228,8 @@ public void testCustomSerializerInvokedForPrimitives() { } }) .create(); - assertEquals("1", gson.toJson(true, boolean.class)); - assertEquals("true", gson.toJson(true, Boolean.class)); + assertThat(gson.toJson(true, boolean.class)).isEqualTo("1"); + assertThat(gson.toJson(true, Boolean.class)).isEqualTo("true"); } @Test @@ -245,8 +242,8 @@ public Boolean deserialize(JsonElement json, Type t, JsonDeserializationContext } }) .create(); - assertEquals(Boolean.TRUE, gson.fromJson("1", boolean.class)); - assertEquals(Boolean.TRUE, gson.fromJson("true", Boolean.class)); + assertThat(gson.fromJson("1", boolean.class)).isEqualTo(Boolean.TRUE); + assertThat(gson.fromJson("true", Boolean.class)).isEqualTo(Boolean.TRUE); } @Test @@ -263,7 +260,7 @@ public JsonElement serialize(byte[] src, Type typeOfSrc, JsonSerializationContex }).create(); byte[] data = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; String json = gson.toJson(data); - assertEquals("\"0123456789\"", json); + assertThat(json).isEqualTo("\"0123456789\""); } @Test @@ -285,7 +282,7 @@ public void testCustomByteArrayDeserializerAndInstanceCreator() { byte[] actual = gson.fromJson(json, byte[].class); byte[] expected = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; for (int i = 0; i < actual.length; ++i) { - assertEquals(expected[i], actual[i]); + assertThat(actual[i]).isEqualTo(expected[i]); } } @@ -335,7 +332,7 @@ public void testCustomAdapterInvokedForCollectionElementSerializationWithType() Set setOfHolders = new HashSet<>(); setOfHolders.add(holder); String json = gson.toJson(setOfHolders, setType); - assertTrue(json.contains("Jacob:Tomaw")); + assertThat(json.contains("Jacob:Tomaw")).isTrue(); } // Test created from Issue 70 @@ -348,7 +345,7 @@ public void testCustomAdapterInvokedForCollectionElementSerialization() { Set setOfHolders = new HashSet<>(); setOfHolders.add(holder); String json = gson.toJson(setOfHolders); - assertTrue(json.contains("Jacob:Tomaw")); + assertThat(json.contains("Jacob:Tomaw")).isTrue(); } // Test created from Issue 70 @@ -359,10 +356,10 @@ public void testCustomAdapterInvokedForCollectionElementDeserialization() { .create(); Type setType = new TypeToken>() {}.getType(); Set setOfHolders = gson.fromJson("['Jacob:Tomaw']", setType); - assertEquals(1, setOfHolders.size()); + assertThat(setOfHolders.size()).isEqualTo(1); StringHolder foo = setOfHolders.iterator().next(); - assertEquals("Jacob", foo.part1); - assertEquals("Tomaw", foo.part2); + assertThat(foo.part1).isEqualTo("Jacob"); + assertThat(foo.part2).isEqualTo("Tomaw"); } // Test created from Issue 70 @@ -376,7 +373,7 @@ public void testCustomAdapterInvokedForMapElementSerializationWithType() { Map mapOfHolders = new HashMap<>(); mapOfHolders.put("foo", holder); String json = gson.toJson(mapOfHolders, mapType); - assertTrue(json.contains("\"foo\":\"Jacob:Tomaw\"")); + assertThat(json.contains("\"foo\":\"Jacob:Tomaw\"")).isTrue(); } // Test created from Issue 70 @@ -389,7 +386,7 @@ public void testCustomAdapterInvokedForMapElementSerialization() { Map mapOfHolders = new HashMap<>(); mapOfHolders.put("foo", holder); String json = gson.toJson(mapOfHolders); - assertTrue(json.contains("\"foo\":\"Jacob:Tomaw\"")); + assertThat(json.contains("\"foo\":\"Jacob:Tomaw\"")).isTrue(); } // Test created from Issue 70 @@ -400,10 +397,10 @@ public void testCustomAdapterInvokedForMapElementDeserialization() { .create(); Type mapType = new TypeToken>() {}.getType(); Map mapOfFoo = gson.fromJson("{'foo':'Jacob:Tomaw'}", mapType); - assertEquals(1, mapOfFoo.size()); + assertThat(mapOfFoo.size()).isEqualTo(1); StringHolder foo = mapOfFoo.get("foo"); - assertEquals("Jacob", foo.part1); - assertEquals("Tomaw", foo.part2); + assertThat(foo.part1).isEqualTo("Jacob"); + assertThat(foo.part2).isEqualTo("Tomaw"); } @Test @@ -413,7 +410,7 @@ public void testEnsureCustomSerializerNotInvokedForNullValues() { .create(); DataHolderWrapper target = new DataHolderWrapper(new DataHolder("abc")); String json = gson.toJson(target); - assertEquals("{\"wrappedData\":{\"myData\":\"abc\"}}", json); + assertThat(json).isEqualTo("{\"wrappedData\":{\"myData\":\"abc\"}}"); } @Test @@ -423,7 +420,7 @@ public void testEnsureCustomDeserializerNotInvokedForNullValues() { .create(); String json = "{wrappedData:null}"; DataHolderWrapper actual = gson.fromJson(json, DataHolderWrapper.class); - assertNull(actual.wrappedData); + assertThat(actual.wrappedData).isNull(); } // Test created from Issue 352 @@ -432,10 +429,10 @@ public void testRegisterHierarchyAdapterForDate() { Gson gson = new GsonBuilder() .registerTypeHierarchyAdapter(Date.class, new DateTypeAdapter()) .create(); - assertEquals("0", gson.toJson(new Date(0))); - assertEquals("0", gson.toJson(new java.sql.Date(0))); - assertEquals(new Date(0), gson.fromJson("0", Date.class)); - assertEquals(new java.sql.Date(0), gson.fromJson("0", java.sql.Date.class)); + assertThat(gson.toJson(new Date(0))).isEqualTo("0"); + assertThat(gson.toJson(new java.sql.Date(0))).isEqualTo("0"); + assertThat(gson.fromJson("0", Date.class)).isEqualTo(new Date(0)); + assertThat(gson.fromJson("0", java.sql.Date.class)).isEqualTo(new java.sql.Date(0)); } private static class DataHolder { diff --git a/gson/src/test/java/com/google/gson/functional/DefaultTypeAdaptersTest.java b/gson/src/test/java/com/google/gson/functional/DefaultTypeAdaptersTest.java index 623bc55ce7..752a7d0630 100644 --- a/gson/src/test/java/com/google/gson/functional/DefaultTypeAdaptersTest.java +++ b/gson/src/test/java/com/google/gson/functional/DefaultTypeAdaptersTest.java @@ -15,9 +15,7 @@ */ package com.google.gson.functional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.fail; import com.google.gson.Gson; @@ -85,7 +83,7 @@ public void setUp() throws Exception { } @After - public void tearDown() throws Exception { + public void tearDown() { TimeZone.setDefault(oldTimeZone); Locale.setDefault(oldLocale); } @@ -99,7 +97,7 @@ public void testClassSerialization() { } // Override with a custom type adapter for class. gson = new GsonBuilder().registerTypeAdapter(Class.class, new MyClassTypeAdapter()).create(); - assertEquals("\"java.lang.String\"", gson.toJson(String.class)); + assertThat(gson.toJson(String.class)).isEqualTo("\"java.lang.String\""); } @Test @@ -111,14 +109,14 @@ public void testClassDeserialization() { } // Override with a custom type adapter for class. gson = new GsonBuilder().registerTypeAdapter(Class.class, new MyClassTypeAdapter()).create(); - assertEquals(String.class, gson.fromJson("java.lang.String", Class.class)); + assertThat(gson.fromJson("java.lang.String", Class.class)).isAssignableTo(String.class); } @Test public void testUrlSerialization() throws Exception { String urlValue = "http://google.com/"; URL url = new URL(urlValue); - assertEquals("\"http://google.com/\"", gson.toJson(url)); + assertThat(gson.toJson(url)).isEqualTo("\"http://google.com/\""); } @Test @@ -126,23 +124,23 @@ public void testUrlDeserialization() { String urlValue = "http://google.com/"; String json = "'http:\\/\\/google.com\\/'"; URL target = gson.fromJson(json, URL.class); - assertEquals(urlValue, target.toExternalForm()); + assertThat(target.toExternalForm()).isEqualTo(urlValue); gson.fromJson('"' + urlValue + '"', URL.class); - assertEquals(urlValue, target.toExternalForm()); + assertThat(target.toExternalForm()).isEqualTo(urlValue); } @Test - public void testUrlNullSerialization() throws Exception { + public void testUrlNullSerialization() { ClassWithUrlField target = new ClassWithUrlField(); - assertEquals("{}", gson.toJson(target)); + assertThat(gson.toJson(target)).isEqualTo("{}"); } @Test public void testUrlNullDeserialization() { String json = "{}"; ClassWithUrlField target = gson.fromJson(json, ClassWithUrlField.class); - assertNull(target.url); + assertThat(target.url).isNull(); } private static class ClassWithUrlField { @@ -153,7 +151,7 @@ private static class ClassWithUrlField { public void testUriSerialization() throws Exception { String uriValue = "http://google.com/"; URI uri = new URI(uriValue); - assertEquals("\"http://google.com/\"", gson.toJson(uri)); + assertThat(gson.toJson(uri)).isEqualTo("\"http://google.com/\""); } @Test @@ -161,11 +159,11 @@ public void testUriDeserialization() { String uriValue = "http://google.com/"; String json = '"' + uriValue + '"'; URI target = gson.fromJson(json, URI.class); - assertEquals(uriValue, target.toASCIIString()); + assertThat(target.toASCIIString()).isEqualTo(uriValue); } @Test - public void testNullSerialization() throws Exception { + public void testNullSerialization() { testNullSerializationAndDeserialization(Boolean.class); testNullSerializationAndDeserialization(Byte.class); testNullSerializationAndDeserialization(Short.class); @@ -201,15 +199,15 @@ private void testNullSerializationAndDeserialization(Class c) { } public static void testNullSerializationAndDeserialization(Gson gson, Class c) { - assertEquals("null", gson.toJson(null, c)); - assertEquals(null, gson.fromJson("null", c)); + assertThat(gson.toJson(null, c)).isEqualTo("null"); + assertThat(gson.fromJson("null", c)).isEqualTo(null); } @Test - public void testUuidSerialization() throws Exception { + public void testUuidSerialization() { String uuidValue = "c237bec1-19ef-4858-a98e-521cf0aad4c0"; UUID uuid = UUID.fromString(uuidValue); - assertEquals('"' + uuidValue + '"', gson.toJson(uuid)); + assertThat(gson.toJson(uuid)).isEqualTo('"' + uuidValue + '"'); } @Test @@ -217,49 +215,49 @@ public void testUuidDeserialization() { String uuidValue = "c237bec1-19ef-4858-a98e-521cf0aad4c0"; String json = '"' + uuidValue + '"'; UUID target = gson.fromJson(json, UUID.class); - assertEquals(uuidValue, target.toString()); + assertThat(target.toString()).isEqualTo(uuidValue); } @Test public void testLocaleSerializationWithLanguage() { Locale target = new Locale("en"); - assertEquals("\"en\"", gson.toJson(target)); + assertThat(gson.toJson(target)).isEqualTo("\"en\""); } @Test public void testLocaleDeserializationWithLanguage() { String json = "\"en\""; Locale locale = gson.fromJson(json, Locale.class); - assertEquals("en", locale.getLanguage()); + assertThat(locale.getLanguage()).isEqualTo("en"); } @Test public void testLocaleSerializationWithLanguageCountry() { Locale target = Locale.CANADA_FRENCH; - assertEquals("\"fr_CA\"", gson.toJson(target)); + assertThat(gson.toJson(target)).isEqualTo("\"fr_CA\""); } @Test public void testLocaleDeserializationWithLanguageCountry() { String json = "\"fr_CA\""; Locale locale = gson.fromJson(json, Locale.class); - assertEquals(Locale.CANADA_FRENCH, locale); + assertThat(locale).isEqualTo(Locale.CANADA_FRENCH); } @Test public void testLocaleSerializationWithLanguageCountryVariant() { Locale target = new Locale("de", "DE", "EURO"); String json = gson.toJson(target); - assertEquals("\"de_DE_EURO\"", json); + assertThat(json).isEqualTo("\"de_DE_EURO\""); } @Test public void testLocaleDeserializationWithLanguageCountryVariant() { String json = "\"de_DE_EURO\""; Locale locale = gson.fromJson(json, Locale.class); - assertEquals("de", locale.getLanguage()); - assertEquals("DE", locale.getCountry()); - assertEquals("EURO", locale.getVariant()); + assertThat(locale.getLanguage()).isEqualTo("de"); + assertThat(locale.getCountry()).isEqualTo("DE"); + assertThat(locale.getVariant()).isEqualTo("EURO"); } @Test @@ -267,7 +265,7 @@ public void testBigDecimalFieldSerialization() { ClassWithBigDecimal target = new ClassWithBigDecimal("-122.01e-21"); String json = gson.toJson(target); String actual = json.substring(json.indexOf(':') + 1, json.indexOf('}')); - assertEquals(target.value, new BigDecimal(actual)); + assertThat(new BigDecimal(actual)).isEqualTo(target.value); } @Test @@ -275,7 +273,7 @@ public void testBigDecimalFieldDeserialization() { ClassWithBigDecimal expected = new ClassWithBigDecimal("-122.01e-21"); String json = expected.getExpectedJson(); ClassWithBigDecimal actual = gson.fromJson(json, ClassWithBigDecimal.class); - assertEquals(expected.value, actual.value); + assertThat(actual.value).isEqualTo(expected.value); } @Test @@ -290,7 +288,7 @@ public void testBadValueForBigDecimalDeserialization() { public void testBigIntegerFieldSerialization() { ClassWithBigInteger target = new ClassWithBigInteger("23232323215323234234324324324324324324"); String json = gson.toJson(target); - assertEquals(target.getExpectedJson(), json); + assertThat(json).isEqualTo(target.getExpectedJson()); } @Test @@ -298,7 +296,7 @@ public void testBigIntegerFieldDeserialization() { ClassWithBigInteger expected = new ClassWithBigInteger("879697697697697697697697697697697697"); String json = expected.getExpectedJson(); ClassWithBigInteger actual = gson.fromJson(json, ClassWithBigInteger.class); - assertEquals(expected.value, actual.value); + assertThat(actual.value).isEqualTo(expected.value); } @Test @@ -306,8 +304,8 @@ public void testOverrideBigIntegerTypeAdapter() throws Exception { gson = new GsonBuilder() .registerTypeAdapter(BigInteger.class, new NumberAsStringAdapter(BigInteger.class)) .create(); - assertEquals("\"123\"", gson.toJson(new BigInteger("123"), BigInteger.class)); - assertEquals(new BigInteger("123"), gson.fromJson("\"123\"", BigInteger.class)); + assertThat(gson.toJson(new BigInteger("123"), BigInteger.class)).isEqualTo("\"123\""); + assertThat(gson.fromJson("\"123\"", BigInteger.class)).isEqualTo(new BigInteger("123")); } @Test @@ -315,35 +313,35 @@ public void testOverrideBigDecimalTypeAdapter() throws Exception { gson = new GsonBuilder() .registerTypeAdapter(BigDecimal.class, new NumberAsStringAdapter(BigDecimal.class)) .create(); - assertEquals("\"1.1\"", gson.toJson(new BigDecimal("1.1"), BigDecimal.class)); - assertEquals(new BigDecimal("1.1"), gson.fromJson("\"1.1\"", BigDecimal.class)); + assertThat(gson.toJson(new BigDecimal("1.1"), BigDecimal.class)).isEqualTo("\"1.1\""); + assertThat(gson.fromJson("\"1.1\"", BigDecimal.class)).isEqualTo(new BigDecimal("1.1")); } @Test - public void testSetSerialization() throws Exception { + public void testSetSerialization() { Gson gson = new Gson(); HashSet s = new HashSet<>(); s.add("blah"); String json = gson.toJson(s); - assertEquals("[\"blah\"]", json); + assertThat(json).isEqualTo("[\"blah\"]"); json = gson.toJson(s, Set.class); - assertEquals("[\"blah\"]", json); + assertThat(json).isEqualTo("[\"blah\"]"); } @Test - public void testBitSetSerialization() throws Exception { + public void testBitSetSerialization() { Gson gson = new Gson(); BitSet bits = new BitSet(); bits.set(1); bits.set(3, 6); bits.set(9); String json = gson.toJson(bits); - assertEquals("[0,1,0,1,1,1,0,0,0,1]", json); + assertThat(json).isEqualTo("[0,1,0,1,1,1,0,0,0,1]"); } @Test - public void testBitSetDeserialization() throws Exception { + public void testBitSetDeserialization() { BitSet expected = new BitSet(); expected.set(0); expected.set(2, 6); @@ -351,29 +349,29 @@ public void testBitSetDeserialization() throws Exception { Gson gson = new Gson(); String json = gson.toJson(expected); - assertEquals(expected, gson.fromJson(json, BitSet.class)); + assertThat(gson.fromJson(json, BitSet.class)).isEqualTo(expected); json = "[1,0,1,1,1,1,0,0,1,0,0,0]"; - assertEquals(expected, gson.fromJson(json, BitSet.class)); + assertThat(gson.fromJson(json, BitSet.class)).isEqualTo(expected); json = "[\"1\",\"0\",\"1\",\"1\",\"1\",\"1\",\"0\",\"0\",\"1\"]"; - assertEquals(expected, gson.fromJson(json, BitSet.class)); + assertThat(gson.fromJson(json, BitSet.class)).isEqualTo(expected); json = "[true,false,true,true,true,true,false,false,true,false,false]"; - assertEquals(expected, gson.fromJson(json, BitSet.class)); + assertThat(gson.fromJson(json, BitSet.class)).isEqualTo(expected); try { gson.fromJson("[1, []]", BitSet.class); fail(); } catch (JsonSyntaxException e) { - assertEquals("Invalid bitset value type: BEGIN_ARRAY; at path $[1]", e.getMessage()); + assertThat(e.getMessage()).isEqualTo("Invalid bitset value type: BEGIN_ARRAY; at path $[1]"); } try { gson.fromJson("[1, 2]", BitSet.class); fail(); } catch (JsonSyntaxException e) { - assertEquals("Invalid bitset value 2, expected 0 or 1; at path $[1]", e.getMessage()); + assertThat(e).hasMessageThat().isEqualTo("Invalid bitset value 2, expected 0 or 1; at path $[1]"); } } @@ -382,9 +380,9 @@ public void testDefaultDateSerialization() { Date now = new Date(1315806903103L); String json = gson.toJson(now); if (JavaVersion.isJava9OrLater()) { - assertEquals("\"Sep 11, 2011, 10:55:03 PM\"", json); + assertThat(json).isEqualTo("\"Sep 11, 2011, 10:55:03 PM\""); } else { - assertEquals("\"Sep 11, 2011 10:55:03 PM\"", json); + assertThat(json).isEqualTo("\"Sep 11, 2011 10:55:03 PM\""); } } @@ -400,114 +398,114 @@ public void testDefaultDateDeserialization() { // millisecond portion. @SuppressWarnings("deprecation") public static void assertEqualsDate(Date date, int year, int month, int day) { - assertEquals(year-1900, date.getYear()); - assertEquals(month, date.getMonth()); - assertEquals(day, date.getDate()); + assertThat(date.getYear()).isEqualTo(year-1900); + assertThat(date.getMonth()).isEqualTo(month); + assertThat(date.getDate()).isEqualTo(day); } @SuppressWarnings("deprecation") public static void assertEqualsTime(Date date, int hours, int minutes, int seconds) { - assertEquals(hours, date.getHours()); - assertEquals(minutes, date.getMinutes()); - assertEquals(seconds, date.getSeconds()); + assertThat(date.getHours()).isEqualTo(hours); + assertThat(date.getMinutes()).isEqualTo(minutes); + assertThat(date.getSeconds()).isEqualTo(seconds); } @Test - public void testDefaultDateSerializationUsingBuilder() throws Exception { + public void testDefaultDateSerializationUsingBuilder() { Gson gson = new GsonBuilder().create(); Date now = new Date(1315806903103L); String json = gson.toJson(now); if (JavaVersion.isJava9OrLater()) { - assertEquals("\"Sep 11, 2011, 10:55:03 PM\"", json); + assertThat(json).isEqualTo("\"Sep 11, 2011, 10:55:03 PM\""); } else { - assertEquals("\"Sep 11, 2011 10:55:03 PM\"", json); + assertThat(json).isEqualTo("\"Sep 11, 2011 10:55:03 PM\""); } } @Test - public void testDefaultDateDeserializationUsingBuilder() throws Exception { + public void testDefaultDateDeserializationUsingBuilder() { Gson gson = new GsonBuilder().create(); Date now = new Date(1315806903103L); String json = gson.toJson(now); Date extracted = gson.fromJson(json, Date.class); - assertEquals(now.toString(), extracted.toString()); + assertThat(extracted.toString()).isEqualTo(now.toString()); } @Test - public void testDefaultCalendarSerialization() throws Exception { + public void testDefaultCalendarSerialization() { Gson gson = new GsonBuilder().create(); String json = gson.toJson(Calendar.getInstance()); - assertTrue(json.contains("year")); - assertTrue(json.contains("month")); - assertTrue(json.contains("dayOfMonth")); - assertTrue(json.contains("hourOfDay")); - assertTrue(json.contains("minute")); - assertTrue(json.contains("second")); + assertThat(json.contains("year")).isTrue(); + assertThat(json.contains("month")).isTrue(); + assertThat(json.contains("dayOfMonth")).isTrue(); + assertThat(json.contains("hourOfDay")).isTrue(); + assertThat(json.contains("minute")).isTrue(); + assertThat(json.contains("second")).isTrue(); } @Test - public void testDefaultCalendarDeserialization() throws Exception { + public void testDefaultCalendarDeserialization() { Gson gson = new GsonBuilder().create(); String json = "{year:2009,month:2,dayOfMonth:11,hourOfDay:14,minute:29,second:23}"; Calendar cal = gson.fromJson(json, Calendar.class); - assertEquals(2009, cal.get(Calendar.YEAR)); - assertEquals(2, cal.get(Calendar.MONTH)); - assertEquals(11, cal.get(Calendar.DAY_OF_MONTH)); - assertEquals(14, cal.get(Calendar.HOUR_OF_DAY)); - assertEquals(29, cal.get(Calendar.MINUTE)); - assertEquals(23, cal.get(Calendar.SECOND)); + assertThat(cal.get(Calendar.YEAR)).isEqualTo(2009); + assertThat(cal.get(Calendar.MONTH)).isEqualTo(2); + assertThat(cal.get(Calendar.DAY_OF_MONTH)).isEqualTo(11); + assertThat(cal.get(Calendar.HOUR_OF_DAY)).isEqualTo(14); + assertThat(cal.get(Calendar.MINUTE)).isEqualTo(29); + assertThat(cal.get(Calendar.SECOND)).isEqualTo(23); } @Test - public void testDefaultGregorianCalendarSerialization() throws Exception { + public void testDefaultGregorianCalendarSerialization() { Gson gson = new GsonBuilder().create(); GregorianCalendar cal = new GregorianCalendar(); String json = gson.toJson(cal); - assertTrue(json.contains("year")); - assertTrue(json.contains("month")); - assertTrue(json.contains("dayOfMonth")); - assertTrue(json.contains("hourOfDay")); - assertTrue(json.contains("minute")); - assertTrue(json.contains("second")); + assertThat(json.contains("year")).isTrue(); + assertThat(json.contains("month")).isTrue(); + assertThat(json.contains("dayOfMonth")).isTrue(); + assertThat(json.contains("hourOfDay")).isTrue(); + assertThat(json.contains("minute")).isTrue(); + assertThat(json.contains("second")).isTrue(); } @Test - public void testDefaultGregorianCalendarDeserialization() throws Exception { + public void testDefaultGregorianCalendarDeserialization() { Gson gson = new GsonBuilder().create(); String json = "{year:2009,month:2,dayOfMonth:11,hourOfDay:14,minute:29,second:23}"; GregorianCalendar cal = gson.fromJson(json, GregorianCalendar.class); - assertEquals(2009, cal.get(Calendar.YEAR)); - assertEquals(2, cal.get(Calendar.MONTH)); - assertEquals(11, cal.get(Calendar.DAY_OF_MONTH)); - assertEquals(14, cal.get(Calendar.HOUR_OF_DAY)); - assertEquals(29, cal.get(Calendar.MINUTE)); - assertEquals(23, cal.get(Calendar.SECOND)); + assertThat(cal.get(Calendar.YEAR)).isEqualTo(2009); + assertThat(cal.get(Calendar.MONTH)).isEqualTo(2); + assertThat(cal.get(Calendar.DAY_OF_MONTH)).isEqualTo(11); + assertThat(cal.get(Calendar.HOUR_OF_DAY)).isEqualTo(14); + assertThat(cal.get(Calendar.MINUTE)).isEqualTo(29); + assertThat(cal.get(Calendar.SECOND)).isEqualTo(23); } @Test - public void testDateSerializationWithPattern() throws Exception { + public void testDateSerializationWithPattern() { String pattern = "yyyy-MM-dd"; Gson gson = new GsonBuilder().setDateFormat(DateFormat.FULL).setDateFormat(pattern).create(); Date now = new Date(1315806903103L); String json = gson.toJson(now); - assertEquals("\"2011-09-11\"", json); + assertThat(json).isEqualTo("\"2011-09-11\""); } @SuppressWarnings("deprecation") @Test - public void testDateDeserializationWithPattern() throws Exception { + public void testDateDeserializationWithPattern() { String pattern = "yyyy-MM-dd"; Gson gson = new GsonBuilder().setDateFormat(DateFormat.FULL).setDateFormat(pattern).create(); Date now = new Date(1315806903103L); String json = gson.toJson(now); Date extracted = gson.fromJson(json, Date.class); - assertEquals(now.getYear(), extracted.getYear()); - assertEquals(now.getMonth(), extracted.getMonth()); - assertEquals(now.getDay(), extracted.getDay()); + assertThat(extracted.getYear()).isEqualTo(now.getYear()); + assertThat(extracted.getMonth()).isEqualTo(now.getMonth()); + assertThat(extracted.getDay()).isEqualTo(now.getDay()); } @Test - public void testDateSerializationWithPatternNotOverridenByTypeAdapter() throws Exception { + public void testDateSerializationWithPatternNotOverridenByTypeAdapter() { String pattern = "yyyy-MM-dd"; Gson gson = new GsonBuilder() .setDateFormat(pattern) @@ -522,12 +520,12 @@ public void testDateSerializationWithPatternNotOverridenByTypeAdapter() throws E Date now = new Date(1315806903103L); String json = gson.toJson(now); - assertEquals("\"2011-09-11\"", json); + assertThat(json).isEqualTo("\"2011-09-11\""); } // http://code.google.com/p/google-gson/issues/detail?id=230 @Test - public void testDateSerializationInCollection() throws Exception { + public void testDateSerializationInCollection() { Type listOfDates = new TypeToken>() {}.getType(); TimeZone defaultTimeZone = TimeZone.getDefault(); TimeZone.setDefault(TimeZone.getTimeZone("UTC")); @@ -537,8 +535,8 @@ public void testDateSerializationInCollection() throws Exception { Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create(); List dates = Arrays.asList(new Date(0)); String json = gson.toJson(dates, listOfDates); - assertEquals("[\"1970-01-01\"]", json); - assertEquals(0L, gson.>fromJson("[\"1970-01-01\"]", listOfDates).get(0).getTime()); + assertThat(json).isEqualTo("[\"1970-01-01\"]"); + assertThat(gson.>fromJson("[\"1970-01-01\"]", listOfDates).get(0).getTime()).isEqualTo(0L); } finally { TimeZone.setDefault(defaultTimeZone); Locale.setDefault(defaultLocale); @@ -547,34 +545,34 @@ public void testDateSerializationInCollection() throws Exception { @Test public void testJsonPrimitiveSerialization() { - assertEquals("5", gson.toJson(new JsonPrimitive(5), JsonElement.class)); - assertEquals("true", gson.toJson(new JsonPrimitive(true), JsonElement.class)); - assertEquals("\"foo\"", gson.toJson(new JsonPrimitive("foo"), JsonElement.class)); - assertEquals("\"a\"", gson.toJson(new JsonPrimitive('a'), JsonElement.class)); + assertThat(gson.toJson(new JsonPrimitive(5), JsonElement.class)).isEqualTo("5"); + assertThat(gson.toJson(new JsonPrimitive(true), JsonElement.class)).isEqualTo("true"); + assertThat(gson.toJson(new JsonPrimitive("foo"), JsonElement.class)).isEqualTo("\"foo\""); + assertThat(gson.toJson(new JsonPrimitive('a'), JsonElement.class)).isEqualTo("\"a\""); } @Test public void testJsonPrimitiveDeserialization() { - assertEquals(new JsonPrimitive(5), gson.fromJson("5", JsonElement.class)); - assertEquals(new JsonPrimitive(5), gson.fromJson("5", JsonPrimitive.class)); - assertEquals(new JsonPrimitive(true), gson.fromJson("true", JsonElement.class)); - assertEquals(new JsonPrimitive(true), gson.fromJson("true", JsonPrimitive.class)); - assertEquals(new JsonPrimitive("foo"), gson.fromJson("\"foo\"", JsonElement.class)); - assertEquals(new JsonPrimitive("foo"), gson.fromJson("\"foo\"", JsonPrimitive.class)); - assertEquals(new JsonPrimitive('a'), gson.fromJson("\"a\"", JsonElement.class)); - assertEquals(new JsonPrimitive('a'), gson.fromJson("\"a\"", JsonPrimitive.class)); + assertThat(gson.fromJson("5", JsonElement.class)).isEqualTo(new JsonPrimitive(5)); + assertThat(gson.fromJson("5", JsonPrimitive.class)).isEqualTo(new JsonPrimitive(5)); + assertThat(gson.fromJson("true", JsonElement.class)).isEqualTo(new JsonPrimitive(true)); + assertThat(gson.fromJson("true", JsonPrimitive.class)).isEqualTo(new JsonPrimitive(true)); + assertThat(gson.fromJson("\"foo\"", JsonElement.class)).isEqualTo(new JsonPrimitive("foo")); + assertThat(gson.fromJson("\"foo\"", JsonPrimitive.class)).isEqualTo(new JsonPrimitive("foo")); + assertThat(gson.fromJson("\"a\"", JsonElement.class)).isEqualTo(new JsonPrimitive('a')); + assertThat(gson.fromJson("\"a\"", JsonPrimitive.class)).isEqualTo(new JsonPrimitive('a')); } @Test public void testJsonNullSerialization() { - assertEquals("null", gson.toJson(JsonNull.INSTANCE, JsonElement.class)); - assertEquals("null", gson.toJson(JsonNull.INSTANCE, JsonNull.class)); + assertThat(gson.toJson(JsonNull.INSTANCE, JsonElement.class)).isEqualTo("null"); + assertThat(gson.toJson(JsonNull.INSTANCE, JsonNull.class)).isEqualTo("null"); } @Test public void testNullJsonElementSerialization() { - assertEquals("null", gson.toJson(null, JsonElement.class)); - assertEquals("null", gson.toJson(null, JsonNull.class)); + assertThat(gson.toJson(null, JsonElement.class)).isEqualTo("null"); + assertThat(gson.toJson(null, JsonNull.class)).isEqualTo("null"); } @Test @@ -583,7 +581,7 @@ public void testJsonArraySerialization() { array.add(new JsonPrimitive(1)); array.add(new JsonPrimitive(2)); array.add(new JsonPrimitive(3)); - assertEquals("[1,2,3]", gson.toJson(array, JsonElement.class)); + assertThat(gson.toJson(array, JsonElement.class)).isEqualTo("[1,2,3]"); } @Test @@ -594,8 +592,8 @@ public void testJsonArrayDeserialization() { array.add(new JsonPrimitive(3)); String json = "[1,2,3]"; - assertEquals(array, gson.fromJson(json, JsonElement.class)); - assertEquals(array, gson.fromJson(json, JsonArray.class)); + assertThat(gson.fromJson(json, JsonElement.class)).isEqualTo(array); + assertThat(gson.fromJson(json, JsonArray.class)).isEqualTo(array); } @Test @@ -603,7 +601,7 @@ public void testJsonObjectSerialization() { JsonObject object = new JsonObject(); object.add("foo", new JsonPrimitive(1)); object.add("bar", new JsonPrimitive(2)); - assertEquals("{\"foo\":1,\"bar\":2}", gson.toJson(object, JsonElement.class)); + assertThat(gson.toJson(object, JsonElement.class)).isEqualTo("{\"foo\":1,\"bar\":2}"); } @Test @@ -614,16 +612,16 @@ public void testJsonObjectDeserialization() { String json = "{\"foo\":1,\"bar\":2}"; JsonElement actual = gson.fromJson(json, JsonElement.class); - assertEquals(object, actual); + assertThat(actual).isEqualTo(object); JsonObject actualObj = gson.fromJson(json, JsonObject.class); - assertEquals(object, actualObj); + assertThat(actualObj).isEqualTo(object); } @Test public void testJsonNullDeserialization() { - assertEquals(JsonNull.INSTANCE, gson.fromJson("null", JsonElement.class)); - assertEquals(JsonNull.INSTANCE, gson.fromJson("null", JsonNull.class)); + assertThat(gson.fromJson("null", JsonElement.class)).isEqualTo(JsonNull.INSTANCE); + assertThat(gson.fromJson("null", JsonNull.class)).isEqualTo(JsonNull.INSTANCE); } @Test @@ -632,8 +630,7 @@ public void testJsonElementTypeMismatch() { gson.fromJson("\"abc\"", JsonObject.class); fail(); } catch (JsonSyntaxException expected) { - assertEquals("Expected a com.google.gson.JsonObject but was com.google.gson.JsonPrimitive; at path $", - expected.getMessage()); + assertThat(expected.getMessage()).isEqualTo("Expected a com.google.gson.JsonObject but was com.google.gson.JsonPrimitive; at path $"); } } @@ -663,14 +660,14 @@ public void testPropertiesSerialization() { props.setProperty("foo", "bar"); String json = gson.toJson(props); String expected = "{\"foo\":\"bar\"}"; - assertEquals(expected, json); + assertThat(json).isEqualTo(expected); } @Test public void testPropertiesDeserialization() { String json = "{foo:'bar'}"; Properties props = gson.fromJson(json, Properties.class); - assertEquals("bar", props.getProperty("foo")); + assertThat(props.getProperty("foo")).isEqualTo("bar"); } @Test @@ -678,7 +675,7 @@ public void testTreeSetSerialization() { TreeSet treeSet = new TreeSet<>(); treeSet.add("Value1"); String json = gson.toJson(treeSet); - assertEquals("[\"Value1\"]", json); + assertThat(json).isEqualTo("[\"Value1\"]"); } @Test @@ -686,33 +683,33 @@ public void testTreeSetDeserialization() { String json = "['Value1']"; Type type = new TypeToken>() {}.getType(); TreeSet treeSet = gson.fromJson(json, type); - assertTrue(treeSet.contains("Value1")); + assertThat(treeSet.contains("Value1")).isTrue(); } @Test public void testStringBuilderSerialization() { StringBuilder sb = new StringBuilder("abc"); String json = gson.toJson(sb); - assertEquals("\"abc\"", json); + assertThat(json).isEqualTo("\"abc\""); } @Test public void testStringBuilderDeserialization() { StringBuilder sb = gson.fromJson("'abc'", StringBuilder.class); - assertEquals("abc", sb.toString()); + assertThat(sb.toString()).isEqualTo("abc"); } @Test public void testStringBufferSerialization() { StringBuffer sb = new StringBuffer("abc"); String json = gson.toJson(sb); - assertEquals("\"abc\"", json); + assertThat(json).isEqualTo("\"abc\""); } @Test public void testStringBufferDeserialization() { StringBuffer sb = gson.fromJson("'abc'", StringBuffer.class); - assertEquals("abc", sb.toString()); + assertThat(sb.toString()).isEqualTo("abc"); } private static class MyClassTypeAdapter extends TypeAdapter> { diff --git a/gson/src/test/java/com/google/gson/functional/DelegateTypeAdapterTest.java b/gson/src/test/java/com/google/gson/functional/DelegateTypeAdapterTest.java index 68e7c36321..32cf86807f 100644 --- a/gson/src/test/java/com/google/gson/functional/DelegateTypeAdapterTest.java +++ b/gson/src/test/java/com/google/gson/functional/DelegateTypeAdapterTest.java @@ -15,7 +15,7 @@ */ package com.google.gson.functional; -import static org.junit.Assert.assertEquals; +import static com.google.common.truth.Truth.assertThat; import com.google.gson.Gson; import com.google.gson.GsonBuilder; @@ -58,8 +58,8 @@ public void testDelegateInvoked() { String json = gson.toJson(bags); bags = gson.fromJson(json, new TypeToken>(){}.getType()); // 11: 1 list object, and 10 entries. stats invoked on all 5 fields - assertEquals(51, stats.numReads); - assertEquals(51, stats.numWrites); + assertThat(stats.numReads).isEqualTo(51); + assertThat(stats.numWrites).isEqualTo(51); } @Test @@ -68,8 +68,8 @@ public void testDelegateInvokedOnStrings() { String json = gson.toJson(bags); bags = gson.fromJson(json, String[].class); // 1 array object with 4 elements. - assertEquals(5, stats.numReads); - assertEquals(5, stats.numWrites); + assertThat(stats.numReads).isEqualTo(5); + assertThat(stats.numWrites).isEqualTo(5); } private static class StatsTypeAdapterFactory implements TypeAdapterFactory { diff --git a/gson/src/test/java/com/google/gson/functional/EnumTest.java b/gson/src/test/java/com/google/gson/functional/EnumTest.java index 7bb306d04e..afe3b029da 100644 --- a/gson/src/test/java/com/google/gson/functional/EnumTest.java +++ b/gson/src/test/java/com/google/gson/functional/EnumTest.java @@ -16,10 +16,7 @@ package com.google.gson.functional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static com.google.common.truth.Truth.assertThat; import com.google.gson.Gson; import com.google.gson.GsonBuilder; @@ -60,15 +57,15 @@ public void setUp() throws Exception { } @Test - public void testTopLevelEnumSerialization() throws Exception { + public void testTopLevelEnumSerialization() { String result = gson.toJson(MyEnum.VALUE1); - assertEquals('"' + MyEnum.VALUE1.toString() + '"', result); + assertThat(result).isEqualTo('"' + MyEnum.VALUE1.toString() + '"'); } @Test - public void testTopLevelEnumDeserialization() throws Exception { + public void testTopLevelEnumDeserialization() { MyEnum result = gson.fromJson('"' + MyEnum.VALUE1.toString() + '"', MyEnum.class); - assertEquals(MyEnum.VALUE1, result); + assertThat(result).isEqualTo(MyEnum.VALUE1); } @Test @@ -79,9 +76,9 @@ public void testCollectionOfEnumsSerialization() { target.add(MyEnum.VALUE2); String expectedJson = "[\"VALUE1\",\"VALUE2\"]"; String actualJson = gson.toJson(target); - assertEquals(expectedJson, actualJson); + assertThat(actualJson).isEqualTo(expectedJson); actualJson = gson.toJson(target, type); - assertEquals(expectedJson, actualJson); + assertThat(actualJson).isEqualTo(expectedJson); } @Test @@ -94,17 +91,17 @@ public void testCollectionOfEnumsDeserialization() { } @Test - public void testClassWithEnumFieldSerialization() throws Exception { + public void testClassWithEnumFieldSerialization() { ClassWithEnumFields target = new ClassWithEnumFields(); - assertEquals(target.getExpectedJson(), gson.toJson(target)); + assertThat(gson.toJson(target)).isEqualTo(target.getExpectedJson()); } @Test - public void testClassWithEnumFieldDeserialization() throws Exception { + public void testClassWithEnumFieldDeserialization() { String json = "{value1:'VALUE1',value2:'VALUE2'}"; ClassWithEnumFields target = gson.fromJson(json, ClassWithEnumFields.class); - assertEquals(MyEnum.VALUE1,target.value1); - assertEquals(MyEnum.VALUE2,target.value2); + assertThat(target.value1).isEqualTo(MyEnum.VALUE1); + assertThat(target.value2).isEqualTo(MyEnum.VALUE2); } private static enum MyEnum { @@ -124,12 +121,13 @@ public String getExpectedJson() { */ @Test public void testEnumSubclass() { - assertFalse(Roshambo.class == Roshambo.ROCK.getClass()); - assertEquals("\"ROCK\"", gson.toJson(Roshambo.ROCK)); - assertEquals("[\"ROCK\",\"PAPER\",\"SCISSORS\"]", gson.toJson(EnumSet.allOf(Roshambo.class))); - assertEquals(Roshambo.ROCK, gson.fromJson("\"ROCK\"", Roshambo.class)); - assertEquals(EnumSet.allOf(Roshambo.class), - gson.fromJson("[\"ROCK\",\"PAPER\",\"SCISSORS\"]", new TypeToken>() {}.getType())); + assertThat(Roshambo.ROCK.getClass()).isAssignableTo(Roshambo.class); + assertThat(gson.toJson(Roshambo.ROCK)).isEqualTo("\"ROCK\""); + assertThat(gson.toJson(EnumSet.allOf(Roshambo.class))).isEqualTo("[\"ROCK\",\"PAPER\",\"SCISSORS\"]"); + assertThat(gson.fromJson("\"ROCK\"", Roshambo.class)).isEqualTo(Roshambo.ROCK); + assertThat(EnumSet.allOf(Roshambo.class)).isEqualTo( + gson.fromJson("[\"ROCK\",\"PAPER\",\"SCISSORS\"]", new TypeToken>() {}.getType()) + ); } @Test @@ -137,12 +135,13 @@ public void testEnumSubclassWithRegisteredTypeAdapter() { gson = new GsonBuilder() .registerTypeHierarchyAdapter(Roshambo.class, new MyEnumTypeAdapter()) .create(); - assertFalse(Roshambo.class == Roshambo.ROCK.getClass()); - assertEquals("\"123ROCK\"", gson.toJson(Roshambo.ROCK)); - assertEquals("[\"123ROCK\",\"123PAPER\",\"123SCISSORS\"]", gson.toJson(EnumSet.allOf(Roshambo.class))); - assertEquals(Roshambo.ROCK, gson.fromJson("\"123ROCK\"", Roshambo.class)); - assertEquals(EnumSet.allOf(Roshambo.class), - gson.fromJson("[\"123ROCK\",\"123PAPER\",\"123SCISSORS\"]", new TypeToken>() {}.getType())); + assertThat(Roshambo.ROCK.getClass()).isAssignableTo(Roshambo.class); + assertThat(gson.toJson(Roshambo.ROCK)).isEqualTo("\"123ROCK\""); + assertThat(gson.toJson(EnumSet.allOf(Roshambo.class))).isEqualTo("[\"123ROCK\",\"123PAPER\",\"123SCISSORS\"]"); + assertThat(gson.fromJson("\"123ROCK\"", Roshambo.class)).isEqualTo(Roshambo.ROCK); + assertThat(EnumSet.allOf(Roshambo.class)).isEqualTo( + gson.fromJson("[\"123ROCK\",\"123PAPER\",\"123SCISSORS\"]", new TypeToken>() {}.getType()) + ); } @Test @@ -152,7 +151,7 @@ public void testEnumSubclassAsParameterizedType() { list.add(Roshambo.PAPER); String json = gson.toJson(list); - assertEquals("[\"ROCK\",\"PAPER\"]", json); + assertThat(json).isEqualTo("[\"ROCK\",\"PAPER\"]"); Type collectionType = new TypeToken>() {}.getType(); Collection actualJsonList = gson.fromJson(json, collectionType); @@ -162,34 +161,34 @@ public void testEnumSubclassAsParameterizedType() { @Test public void testEnumCaseMapping() { - assertEquals(Gender.MALE, gson.fromJson("\"boy\"", Gender.class)); - assertEquals("\"boy\"", gson.toJson(Gender.MALE, Gender.class)); + assertThat(gson.fromJson("\"boy\"", Gender.class)).isEqualTo(Gender.MALE); + assertThat(gson.toJson(Gender.MALE, Gender.class)).isEqualTo("\"boy\""); } @Test public void testEnumSet() { EnumSet foo = EnumSet.of(Roshambo.ROCK, Roshambo.PAPER); String json = gson.toJson(foo); - assertEquals("[\"ROCK\",\"PAPER\"]", json); + assertThat(json).isEqualTo("[\"ROCK\",\"PAPER\"]"); Type type = new TypeToken>() {}.getType(); EnumSet bar = gson.fromJson(json, type); - assertTrue(bar.contains(Roshambo.ROCK)); - assertTrue(bar.contains(Roshambo.PAPER)); - assertFalse(bar.contains(Roshambo.SCISSORS)); + assertThat(bar.contains(Roshambo.ROCK)).isTrue(); + assertThat(bar.contains(Roshambo.PAPER)).isTrue(); + assertThat(bar.contains(Roshambo.SCISSORS)).isFalse(); } @Test - public void testEnumMap() throws Exception { + public void testEnumMap() { EnumMap map = new EnumMap<>(MyEnum.class); map.put(MyEnum.VALUE1, "test"); String json = gson.toJson(map); - assertEquals("{\"VALUE1\":\"test\"}", json); + assertThat(json).isEqualTo("{\"VALUE1\":\"test\"}"); Type type = new TypeToken>() {}.getType(); EnumMap actualMap = gson.fromJson("{\"VALUE1\":\"test\"}", type); Map expectedMap = Collections.singletonMap(MyEnum.VALUE1, "test"); - assertEquals(expectedMap, actualMap); + assertThat(actualMap).isEqualTo(expectedMap); } private enum Roshambo { @@ -234,9 +233,9 @@ private enum Gender { @Test public void testEnumClassWithFields() { - assertEquals("\"RED\"", gson.toJson(Color.RED)); - assertEquals("red", gson.fromJson("RED", Color.class).value); - assertEquals(2, gson.fromJson("BLUE", Color.class).index); + assertThat(gson.toJson(Color.RED)).isEqualTo("\"RED\""); + assertThat(gson.fromJson("RED", Color.class).value).isEqualTo("red"); + assertThat(gson.fromJson("BLUE", Color.class).index).isEqualTo(2); } private enum Color { @@ -252,11 +251,11 @@ private Color(String value, int index) { @Test public void testEnumToStringRead() { // Should still be able to read constant name - assertEquals(CustomToString.A, gson.fromJson("\"A\"", CustomToString.class)); + assertThat(gson.fromJson("\"A\"", CustomToString.class)).isEqualTo(CustomToString.A); // Should be able to read toString() value - assertEquals(CustomToString.A, gson.fromJson("\"test\"", CustomToString.class)); + assertThat(gson.fromJson("\"test\"", CustomToString.class)).isEqualTo(CustomToString.A); - assertNull(gson.fromJson("\"other\"", CustomToString.class)); + assertThat(gson.fromJson("\"other\"", CustomToString.class)).isNull(); } private enum CustomToString { @@ -274,8 +273,8 @@ public String toString() { */ @Test public void testEnumToStringReadInterchanged() { - assertEquals(InterchangedToString.A, gson.fromJson("\"A\"", InterchangedToString.class)); - assertEquals(InterchangedToString.B, gson.fromJson("\"B\"", InterchangedToString.class)); + assertThat(gson.fromJson("\"A\"", InterchangedToString.class)).isEqualTo(InterchangedToString.A); + assertThat(gson.fromJson("\"B\"", InterchangedToString.class)).isEqualTo(InterchangedToString.B); } private enum InterchangedToString { diff --git a/gson/src/test/java/com/google/gson/functional/EnumWithObfuscatedTest.java b/gson/src/test/java/com/google/gson/functional/EnumWithObfuscatedTest.java index 373f0071b4..979316ce71 100644 --- a/gson/src/test/java/com/google/gson/functional/EnumWithObfuscatedTest.java +++ b/gson/src/test/java/com/google/gson/functional/EnumWithObfuscatedTest.java @@ -16,7 +16,7 @@ package com.google.gson.functional; -import static org.junit.Assert.assertEquals; +import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.fail; import com.google.gson.Gson; @@ -55,7 +55,7 @@ public void testEnumClassWithObfuscated() { } } - assertEquals(Gender.MALE, gson.fromJson("\"MAIL\"", Gender.class)); - assertEquals("\"MAIL\"", gson.toJson(Gender.MALE, Gender.class)); + assertThat(gson.fromJson("\"MAIL\"", Gender.class)).isEqualTo(Gender.MALE); + assertThat(gson.toJson(Gender.MALE, Gender.class)).isEqualTo("\"MAIL\""); } } diff --git a/gson/src/test/java/com/google/gson/functional/EscapingTest.java b/gson/src/test/java/com/google/gson/functional/EscapingTest.java index f8c6f4fe09..e917a05af8 100644 --- a/gson/src/test/java/com/google/gson/functional/EscapingTest.java +++ b/gson/src/test/java/com/google/gson/functional/EscapingTest.java @@ -16,9 +16,7 @@ package com.google.gson.functional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static com.google.common.truth.Truth.assertThat; import com.google.gson.Gson; import com.google.gson.GsonBuilder; @@ -43,12 +41,12 @@ public void setUp() throws Exception { } @Test - public void testEscapingQuotesInStringArray() throws Exception { + public void testEscapingQuotesInStringArray() { String[] valueWithQuotes = { "beforeQuote\"afterQuote" }; String jsonRepresentation = gson.toJson(valueWithQuotes); String[] target = gson.fromJson(jsonRepresentation, String[].class); - assertEquals(1, target.length); - assertEquals(valueWithQuotes[0], target[0]); + assertThat(target.length).isEqualTo(1); + assertThat(target[0]).isEqualTo(valueWithQuotes[0]); } @Test @@ -60,34 +58,33 @@ public void testEscapeAllHtmlCharacters() { strings.add("&"); strings.add("'"); strings.add("\""); - assertEquals("[\"\\u003c\",\"\\u003e\",\"\\u003d\",\"\\u0026\",\"\\u0027\",\"\\\"\"]", - gson.toJson(strings)); + assertThat(gson.toJson(strings)).isEqualTo("[\"\\u003c\",\"\\u003e\",\"\\u003d\",\"\\u0026\",\"\\u0027\",\"\\\"\"]"); } @Test - public void testEscapingObjectFields() throws Exception { + public void testEscapingObjectFields() { BagOfPrimitives objWithPrimitives = new BagOfPrimitives(1L, 1, true, "test with\" "; String result = gson.toJson(target); - assertFalse(result.equals('"' + target + '"')); + assertThat(result).isNotEqualTo('"' + target + '"'); gson = new GsonBuilder().disableHtmlEscaping().create(); result = gson.toJson(target); - assertTrue(result.equals('"' + target + '"')); + assertThat(result).isEqualTo('"' + target + '"'); } @Test public void testDeserializePrimitiveWrapperAsObjectField() { String json = "{i:10}"; ClassWithIntegerField target = gson.fromJson(json, ClassWithIntegerField.class); - assertEquals(10, target.i.intValue()); + assertThat(target.i).isEqualTo(10); } private static class ClassWithIntegerField { @@ -800,9 +798,9 @@ private static class ClassWithIntegerField { @Test public void testPrimitiveClassLiteral() { - assertEquals(1, gson.fromJson("1", int.class).intValue()); - assertEquals(1, gson.fromJson(new StringReader("1"), int.class).intValue()); - assertEquals(1, gson.fromJson(new JsonPrimitive(1), int.class).intValue()); + assertThat(gson.fromJson("1", int.class)).isEqualTo(1); + assertThat(gson.fromJson(new StringReader("1"), int.class)).isEqualTo(1); + assertThat(gson.fromJson(new JsonPrimitive(1), int.class)).isEqualTo(1); } @Test @@ -967,7 +965,7 @@ public void testDeserializeJsonObjectAsNumber() { @Test public void testDeserializingDecimalPointValueZeroSucceeds() { - assertEquals(1, (int) gson.fromJson("1.0", Integer.class)); + assertThat(gson.fromJson("1.0", Integer.class)).isEqualTo(1); } @Test @@ -1023,28 +1021,28 @@ public void testDeserializingBigIntegerAsLong() { @Test public void testValueVeryCloseToZeroIsZero() { - assertEquals(0, (byte) gson.fromJson("-122.08e-2132", byte.class)); - assertEquals(0, (short) gson.fromJson("-122.08e-2132", short.class)); - assertEquals(0, (int) gson.fromJson("-122.08e-2132", int.class)); - assertEquals(0, (long) gson.fromJson("-122.08e-2132", long.class)); - assertEquals(-0.0f, gson.fromJson("-122.08e-2132", float.class), 0); - assertEquals(-0.0, gson.fromJson("-122.08e-2132", double.class), 0); - assertEquals(0.0f, gson.fromJson("122.08e-2132", float.class), 0); - assertEquals(0.0, gson.fromJson("122.08e-2132", double.class), 0); + assertThat(gson.fromJson("-122.08e-2132", byte.class)).isEqualTo(0); + assertThat(gson.fromJson("-122.08e-2132", short.class)).isEqualTo(0); + assertThat(gson.fromJson("-122.08e-2132", int.class)).isEqualTo(0); + assertThat(gson.fromJson("-122.08e-2132", long.class)).isEqualTo(0); + assertThat(gson.fromJson("-122.08e-2132", float.class)).isEqualTo(-0.0f); + assertThat(gson.fromJson("-122.08e-2132", double.class)).isEqualTo(-0.0); + assertThat(gson.fromJson("122.08e-2132", float.class)).isEqualTo(0.0f); + assertThat(gson.fromJson("122.08e-2132", double.class)).isEqualTo(0.0); } @Test public void testDeserializingBigDecimalAsFloat() { String json = "-122.08e-2132332"; float actual = gson.fromJson(json, float.class); - assertEquals(-0.0f, actual, 0); + assertThat(actual).isEqualTo(-0.0f); } @Test public void testDeserializingBigDecimalAsDouble() { String json = "-122.08e-2132332"; double actual = gson.fromJson(json, double.class); - assertEquals(-0.0d, actual, 0); + assertThat(actual).isEqualTo(-0.0d); } @Test @@ -1060,13 +1058,12 @@ public void testDeserializingBigDecimalAsBigIntegerFails() { public void testDeserializingBigIntegerAsBigDecimal() { BigDecimal actual = gson.fromJson("12121211243123245845384534687435634558945453489543985435", BigDecimal.class); - assertEquals("12121211243123245845384534687435634558945453489543985435", actual.toPlainString()); + assertThat(actual.toPlainString()).isEqualTo("12121211243123245845384534687435634558945453489543985435"); } @Test public void testStringsAsBooleans() { String json = "['true', 'false', 'TRUE', 'yes', '1']"; - assertEquals(Arrays.asList(true, false, true, false, false), - gson.>fromJson(json, new TypeToken>() {}.getType())); + assertThat( gson.>fromJson(json, new TypeToken>() {}.getType())).isEqualTo(Arrays.asList(true, false, true, false, false)); } } diff --git a/gson/src/test/java/com/google/gson/functional/PrintFormattingTest.java b/gson/src/test/java/com/google/gson/functional/PrintFormattingTest.java index 55d7606c60..d31a43d005 100644 --- a/gson/src/test/java/com/google/gson/functional/PrintFormattingTest.java +++ b/gson/src/test/java/com/google/gson/functional/PrintFormattingTest.java @@ -16,8 +16,7 @@ package com.google.gson.functional; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static com.google.common.truth.Truth.assertThat; import com.google.gson.Gson; import com.google.gson.GsonBuilder; @@ -64,8 +63,8 @@ public void testJsonObjectWithNullValues() { obj.addProperty("field1", "value1"); obj.addProperty("field2", (String) null); String json = gson.toJson(obj); - assertTrue(json.contains("field1")); - assertFalse(json.contains("field2")); + assertThat(json).contains("field1"); + assertThat(json).doesNotContain("field2"); } @Test @@ -75,13 +74,13 @@ public void testJsonObjectWithNullValuesSerialized() { obj.addProperty("field1", "value1"); obj.addProperty("field2", (String) null); String json = gson.toJson(obj); - assertTrue(json.contains("field1")); - assertTrue(json.contains("field2")); + assertThat(json).contains("field1"); + assertThat(json).contains("field2"); } private static void assertContainsNoWhiteSpace(String str) { for (char c : str.toCharArray()) { - assertFalse(Character.isWhitespace(c)); + assertThat(Character.isWhitespace(c)).isFalse(); } } } diff --git a/gson/src/test/java/com/google/gson/functional/RawSerializationTest.java b/gson/src/test/java/com/google/gson/functional/RawSerializationTest.java index 6e7ada6ecb..132eadfffc 100644 --- a/gson/src/test/java/com/google/gson/functional/RawSerializationTest.java +++ b/gson/src/test/java/com/google/gson/functional/RawSerializationTest.java @@ -15,7 +15,7 @@ */ package com.google.gson.functional; -import static org.junit.Assert.assertEquals; +import static com.google.common.truth.Truth.assertThat; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; @@ -42,14 +42,14 @@ public void setUp() throws Exception { public void testCollectionOfPrimitives() { Collection ints = Arrays.asList(1, 2, 3, 4, 5); String json = gson.toJson(ints); - assertEquals("[1,2,3,4,5]", json); + assertThat(json).isEqualTo("[1,2,3,4,5]"); } @Test public void testCollectionOfObjects() { Collection foos = Arrays.asList(new Foo(1), new Foo(2)); String json = gson.toJson(foos); - assertEquals("[{\"b\":1},{\"b\":2}]", json); + assertThat(json).isEqualTo("[{\"b\":1},{\"b\":2}]"); } @Test @@ -58,10 +58,10 @@ public void testParameterizedObject() { String expectedJson = "{\"t\":{\"b\":1}}"; // Ensure that serialization works without specifying the type explicitly String json = gson.toJson(bar); - assertEquals(expectedJson, json); + assertThat(json).isEqualTo(expectedJson); // Ensure that serialization also works when the type is specified explicitly json = gson.toJson(bar, new TypeToken>(){}.getType()); - assertEquals(expectedJson, json); + assertThat(json).isEqualTo(expectedJson); } @Test @@ -70,10 +70,10 @@ public void testTwoLevelParameterizedObject() { String expectedJson = "{\"t\":{\"t\":{\"b\":1}}}"; // Ensure that serialization works without specifying the type explicitly String json = gson.toJson(bar); - assertEquals(expectedJson, json); + assertThat(json).isEqualTo(expectedJson); // Ensure that serialization also works when the type is specified explicitly json = gson.toJson(bar, new TypeToken>>(){}.getType()); - assertEquals(expectedJson, json); + assertThat(json).isEqualTo(expectedJson); } @Test @@ -82,10 +82,10 @@ public void testThreeLevelParameterizedObject() { String expectedJson = "{\"t\":{\"t\":{\"t\":{\"b\":1}}}}"; // Ensure that serialization works without specifying the type explicitly String json = gson.toJson(bar); - assertEquals(expectedJson, json); + assertThat(json).isEqualTo(expectedJson); // Ensure that serialization also works when the type is specified explicitly json = gson.toJson(bar, new TypeToken>>>(){}.getType()); - assertEquals(expectedJson, json); + assertThat(json).isEqualTo(expectedJson); } private static class Foo { diff --git a/gson/src/test/java/com/google/gson/functional/ReadersWritersTest.java b/gson/src/test/java/com/google/gson/functional/ReadersWritersTest.java index 4862cda465..26c6541b77 100644 --- a/gson/src/test/java/com/google/gson/functional/ReadersWritersTest.java +++ b/gson/src/test/java/com/google/gson/functional/ReadersWritersTest.java @@ -15,10 +15,7 @@ */ package com.google.gson.functional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.fail; import com.google.gson.Gson; @@ -54,33 +51,33 @@ public void setUp() throws Exception { } @Test - public void testWriterForSerialization() throws Exception { + public void testWriterForSerialization() { Writer writer = new StringWriter(); BagOfPrimitives src = new BagOfPrimitives(); gson.toJson(src, writer); - assertEquals(src.getExpectedJson(), writer.toString()); + assertThat(writer.toString()).isEqualTo(src.getExpectedJson()); } @Test - public void testReaderForDeserialization() throws Exception { + public void testReaderForDeserialization() { BagOfPrimitives expected = new BagOfPrimitives(); Reader json = new StringReader(expected.getExpectedJson()); BagOfPrimitives actual = gson.fromJson(json, BagOfPrimitives.class); - assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); } @Test public void testTopLevelNullObjectSerializationWithWriter() { StringWriter writer = new StringWriter(); gson.toJson(null, writer); - assertEquals("null", writer.toString()); + assertThat(writer.toString()).isEqualTo("null"); } @Test public void testTopLevelNullObjectDeserializationWithReader() { StringReader reader = new StringReader("null"); Integer nullIntObject = gson.fromJson(reader, Integer.class); - assertNull(nullIntObject); + assertThat(nullIntObject).isNull(); } @Test @@ -88,7 +85,7 @@ public void testTopLevelNullObjectSerializationWithWriterAndSerializeNulls() { Gson gson = new GsonBuilder().serializeNulls().create(); StringWriter writer = new StringWriter(); gson.toJson(null, writer); - assertEquals("null", writer.toString()); + assertThat(writer.toString()).isEqualTo("null"); } @Test @@ -96,7 +93,7 @@ public void testTopLevelNullObjectDeserializationWithReaderAndSerializeNulls() { Gson gson = new GsonBuilder().serializeNulls().create(); StringReader reader = new StringReader("null"); Integer nullIntObject = gson.fromJson(reader, Integer.class); - assertNull(nullIntObject); + assertThat(nullIntObject).isNull(); } @Test @@ -108,9 +105,9 @@ public void testReadWriteTwoStrings() throws IOException { CharArrayReader reader = new CharArrayReader(writer.toCharArray()); JsonStreamParser parser = new JsonStreamParser(reader); String actualOne = gson.fromJson(parser.next(), String.class); - assertEquals("one", actualOne); + assertThat(actualOne).isEqualTo("one"); String actualTwo = gson.fromJson(parser.next(), String.class); - assertEquals("two", actualTwo); + assertThat(actualTwo).isEqualTo("two"); } @Test @@ -124,10 +121,10 @@ public void testReadWriteTwoObjects() throws IOException { CharArrayReader reader = new CharArrayReader(writer.toCharArray()); JsonStreamParser parser = new JsonStreamParser(reader); BagOfPrimitives actualOne = gson.fromJson(parser.next(), BagOfPrimitives.class); - assertEquals("one", actualOne.stringValue); + assertThat(actualOne.stringValue).isEqualTo("one"); BagOfPrimitives actualTwo = gson.fromJson(parser.next(), BagOfPrimitives.class); - assertEquals("two", actualTwo.stringValue); - assertFalse(parser.hasNext()); + assertThat(actualTwo.stringValue).isEqualTo("two"); + assertThat(parser.hasNext()).isFalse(); } @Test @@ -191,7 +188,7 @@ public Appendable append(CharSequence csq, int start, int end) throws IOExceptio gson.toJson(Arrays.asList("test", 123, true), appendable); // Make sure CharSequence.toString() was called at least two times to verify that // CurrentWrite.cachedString is properly overwritten when char array changes - assertTrue(appendable.toStringCallCount >= 2); - assertEquals("[\"test\",123,true]", appendable.stringBuilder.toString()); + assertThat(appendable.toStringCallCount >= 2).isTrue(); + assertThat(appendable.stringBuilder.toString()).isEqualTo("[\"test\",123,true]"); } } diff --git a/gson/src/test/java/com/google/gson/functional/ReflectionAccessFilterTest.java b/gson/src/test/java/com/google/gson/functional/ReflectionAccessFilterTest.java index 6c9ab44945..1d79b38e86 100644 --- a/gson/src/test/java/com/google/gson/functional/ReflectionAccessFilterTest.java +++ b/gson/src/test/java/com/google/gson/functional/ReflectionAccessFilterTest.java @@ -1,8 +1,8 @@ package com.google.gson.functional; -import static org.junit.Assert.assertEquals; +import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.fail; -import static org.junit.Assume.assumeNotNull; +import static org.junit.Assume.assumeNotNull;; import com.google.gson.Gson; import com.google.gson.GsonBuilder; @@ -52,12 +52,10 @@ public void testBlockInaccessibleJava() throws ReflectiveOperationException { fail("Expected exception; test needs to be run with Java >= 9"); } catch (JsonIOException expected) { // Note: This test is rather brittle and depends on the JDK implementation - assertEquals( - "Field 'java.io.File#path' is not accessible and ReflectionAccessFilter does not permit" + assertThat(expected).hasMessageThat() + .isEqualTo("Field 'java.io.File#path' is not accessible and ReflectionAccessFilter does not permit" + " making it accessible. Register a TypeAdapter for the declaring type, adjust the access" - + " filter or increase the visibility of the element and its declaring type.", - expected.getMessage() - ); + + " filter or increase the visibility of the element and its declaring type."); } @@ -72,7 +70,7 @@ public void testBlockInaccessibleJava() throws ReflectiveOperationException { Constructor pointConstructor = pointClass.getConstructor(int.class, int.class); Object point = pointConstructor.newInstance(1, 2); String json = gson.toJson(point); - assertEquals("{\"x\":1,\"y\":2}", json); + assertThat(json).isEqualTo("{\"x\":1,\"y\":2}"); } @Test @@ -85,12 +83,10 @@ public void testBlockInaccessibleJavaExtendingJdkClass() { gson.toJson(new ClassExtendingJdkClass()); fail("Expected exception; test needs to be run with Java >= 9"); } catch (JsonIOException expected) { - assertEquals( - "Field 'java.io.Reader#lock' is not accessible and ReflectionAccessFilter does not permit" - + " making it accessible. Register a TypeAdapter for the declaring type, adjust the access" - + " filter or increase the visibility of the element and its declaring type.", - expected.getMessage() - ); + assertThat(expected).hasMessageThat() + .isEqualTo("Field 'java.io.Reader#lock' is not accessible and ReflectionAccessFilter does not permit" + + " making it accessible. Register a TypeAdapter for the declaring type, adjust the access" + + " filter or increase the visibility of the element and its declaring type."); } } @@ -105,11 +101,9 @@ public void testBlockAllJava() { gson.toJson(Thread.currentThread()); fail(); } catch (JsonIOException expected) { - assertEquals( - "ReflectionAccessFilter does not permit using reflection for class java.lang.Thread." - + " Register a TypeAdapter for this type or adjust the access filter.", - expected.getMessage() - ); + assertThat(expected).hasMessageThat() + .isEqualTo("ReflectionAccessFilter does not permit using reflection for class java.lang.Thread." + + " Register a TypeAdapter for this type or adjust the access filter."); } } @@ -123,12 +117,10 @@ public void testBlockAllJavaExtendingJdkClass() { gson.toJson(new ClassExtendingJdkClass()); fail(); } catch (JsonIOException expected) { - assertEquals( - "ReflectionAccessFilter does not permit using reflection for class java.io.Reader" - + " (supertype of class com.google.gson.functional.ReflectionAccessFilterTest$ClassExtendingJdkClass)." - + " Register a TypeAdapter for this type or adjust the access filter.", - expected.getMessage() - ); + assertThat(expected).hasMessageThat() + .isEqualTo("ReflectionAccessFilter does not permit using reflection for class java.io.Reader" + + " (supertype of class com.google.gson.functional.ReflectionAccessFilterTest$ClassExtendingJdkClass)." + + " Register a TypeAdapter for this type or adjust the access filter."); } } @@ -153,13 +145,11 @@ public void testBlockInaccessibleStaticField() { gson.toJson(new ClassWithStaticField()); fail("Expected exception; test needs to be run with Java >= 9"); } catch (JsonIOException expected) { - assertEquals( - "Field 'com.google.gson.functional.ReflectionAccessFilterTest$ClassWithStaticField#i'" - + " is not accessible and ReflectionAccessFilter does not permit making it accessible." - + " Register a TypeAdapter for the declaring type, adjust the access filter or increase" - + " the visibility of the element and its declaring type.", - expected.getMessage() - ); + assertThat(expected).hasMessageThat() + .isEqualTo("Field 'com.google.gson.functional.ReflectionAccessFilterTest$ClassWithStaticField#i'" + + " is not accessible and ReflectionAccessFilter does not permit making it accessible." + + " Register a TypeAdapter for the declaring type, adjust the access filter or increase" + + " the visibility of the element and its declaring type."); } } @@ -196,21 +186,18 @@ public void testDelegation() { gson.toJson(new SuperTestClass()); fail(); } catch (JsonIOException expected) { - assertEquals( - "ReflectionAccessFilter does not permit using reflection for class" + assertThat(expected).hasMessageThat().isEqualTo("ReflectionAccessFilter does not permit using reflection for class" + " com.google.gson.functional.ReflectionAccessFilterTest$SuperTestClass." - + " Register a TypeAdapter for this type or adjust the access filter.", - expected.getMessage() - ); + + " Register a TypeAdapter for this type or adjust the access filter."); } // But registration order is reversed, so filter for SubTestClass allows reflection String json = gson.toJson(new SubTestClass()); - assertEquals("{\"i\":1}", json); + assertThat(json).isEqualTo("{\"i\":1}"); // And unrelated class should not be affected json = gson.toJson(new OtherClass()); - assertEquals("{\"i\":2}", json); + assertThat(json).isEqualTo("{\"i\":2}"); } private static class ClassWithPrivateField { @@ -235,13 +222,10 @@ public void testAllowForSupertype() { gson.toJson(new ExtendingClassWithPrivateField()); fail("Expected exception; test needs to be run with Java >= 9"); } catch (JsonIOException expected) { - assertEquals( - "Field 'com.google.gson.functional.ReflectionAccessFilterTest$ClassWithPrivateField#i'" + assertThat(expected).hasMessageThat().isEqualTo("Field 'com.google.gson.functional.ReflectionAccessFilterTest$ClassWithPrivateField#i'" + " is not accessible and ReflectionAccessFilter does not permit making it accessible." + " Register a TypeAdapter for the declaring type, adjust the access filter or increase" - + " the visibility of the element and its declaring type.", - expected.getMessage() - ); + + " the visibility of the element and its declaring type."); } gson = gson.newBuilder() @@ -255,7 +239,7 @@ public void testAllowForSupertype() { // Inherited (inaccessible) private field should have been made accessible String json = gson.toJson(new ExtendingClassWithPrivateField()); - assertEquals("{\"i\":1}", json); + assertThat(json).isEqualTo("{\"i\":1}"); } private static class ClassWithPrivateNoArgsConstructor { @@ -277,12 +261,9 @@ public void testInaccessibleNoArgsConstructor() { gson.fromJson("{}", ClassWithPrivateNoArgsConstructor.class); fail("Expected exception; test needs to be run with Java >= 9"); } catch (JsonIOException expected) { - assertEquals( - "Unable to invoke no-args constructor of class com.google.gson.functional.ReflectionAccessFilterTest$ClassWithPrivateNoArgsConstructor;" + assertThat(expected).hasMessageThat().isEqualTo("Unable to invoke no-args constructor of class com.google.gson.functional.ReflectionAccessFilterTest$ClassWithPrivateNoArgsConstructor;" + " constructor is not accessible and ReflectionAccessFilter does not permit making it accessible. Register an" - + " InstanceCreator or a TypeAdapter for this type, change the visibility of the constructor or adjust the access filter.", - expected.getMessage() - ); + + " InstanceCreator or a TypeAdapter for this type, change the visibility of the constructor or adjust the access filter."); } } @@ -309,12 +290,9 @@ public void testClassWithoutNoArgsConstructor() { gson.fromJson("{}", ClassWithoutNoArgsConstructor.class); fail(); } catch (JsonIOException expected) { - assertEquals( - "Unable to create instance of class com.google.gson.functional.ReflectionAccessFilterTest$ClassWithoutNoArgsConstructor;" + assertThat(expected).hasMessageThat().isEqualTo("Unable to create instance of class com.google.gson.functional.ReflectionAccessFilterTest$ClassWithoutNoArgsConstructor;" + " ReflectionAccessFilter does not permit using reflection or Unsafe. Register an InstanceCreator" - + " or a TypeAdapter for this type or adjust the access filter to allow using reflection.", - expected.getMessage() - ); + + " or a TypeAdapter for this type or adjust the access filter to allow using reflection."); } // But should not fail when custom TypeAdapter is specified @@ -324,13 +302,13 @@ public void testClassWithoutNoArgsConstructor() { in.skipValue(); return new ClassWithoutNoArgsConstructor("TypeAdapter"); } - @Override public void write(JsonWriter out, ClassWithoutNoArgsConstructor value) throws IOException { + @Override public void write(JsonWriter out, ClassWithoutNoArgsConstructor value) { throw new AssertionError("Not needed for test"); } }) .create(); ClassWithoutNoArgsConstructor deserialized = gson.fromJson("{}", ClassWithoutNoArgsConstructor.class); - assertEquals("TypeAdapter", deserialized.s); + assertThat(deserialized.s).isEqualTo("TypeAdapter"); // But should not fail when custom InstanceCreator is specified gson = gsonBuilder @@ -341,7 +319,7 @@ public void testClassWithoutNoArgsConstructor() { }) .create(); deserialized = gson.fromJson("{}", ClassWithoutNoArgsConstructor.class); - assertEquals("InstanceCreator", deserialized.s); + assertThat(deserialized.s).isEqualTo("InstanceCreator"); } /** @@ -364,18 +342,15 @@ public void testBlockAllPartial() { .create(); String json = gson.toJson(new OtherClass()); - assertEquals("123", json); + assertThat(json).isEqualTo("123"); // But deserialization should fail try { gson.fromJson("{}", OtherClass.class); fail(); } catch (JsonIOException expected) { - assertEquals( - "ReflectionAccessFilter does not permit using reflection for class com.google.gson.functional.ReflectionAccessFilterTest$OtherClass." - + " Register a TypeAdapter for this type or adjust the access filter.", - expected.getMessage() - ); + assertThat(expected).hasMessageThat().isEqualTo("ReflectionAccessFilter does not permit using reflection for class com.google.gson.functional.ReflectionAccessFilterTest$OtherClass." + + " Register a TypeAdapter for this type or adjust the access filter."); } } @@ -393,7 +368,7 @@ public void testBlockAllCollectionInterface() { }) .create(); List deserialized = gson.fromJson("[1.0]", List.class); - assertEquals(1.0, deserialized.get(0)); + assertThat(deserialized.get(0)).isEqualTo(1.0); } /** @@ -410,7 +385,7 @@ public void testBlockAllCollectionImplementation() { }) .create(); List deserialized = gson.fromJson("[1.0]", LinkedList.class); - assertEquals(1.0, deserialized.get(0)); + assertThat(deserialized.get(0)).isEqualTo(1.0); } /** @@ -431,11 +406,8 @@ public void testBlockInaccessibleInterface() { gson.fromJson("{}", Runnable.class); fail(); } catch (JsonIOException expected) { - assertEquals( - "Interfaces can't be instantiated! Register an InstanceCreator or a TypeAdapter for" - + " this type. Interface name: java.lang.Runnable", - expected.getMessage() - ); + assertThat(expected).hasMessageThat().isEqualTo("Interfaces can't be instantiated! Register an InstanceCreator or a TypeAdapter for" + + " this type. Interface name: java.lang.Runnable"); } } } diff --git a/gson/src/test/java/com/google/gson/functional/ReflectionAccessTest.java b/gson/src/test/java/com/google/gson/functional/ReflectionAccessTest.java index c731a8b581..30c0a2ff25 100644 --- a/gson/src/test/java/com/google/gson/functional/ReflectionAccessTest.java +++ b/gson/src/test/java/com/google/gson/functional/ReflectionAccessTest.java @@ -1,8 +1,6 @@ package com.google.gson.functional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.fail; import com.google.gson.Gson; @@ -65,7 +63,7 @@ public void checkPermission(Permission perm) { gson.getAdapter(clazz); fail(); } catch (SecurityException e) { - assertEquals("Gson: no-member-access", e.getMessage()); + assertThat(e.getMessage()).isEqualTo("Gson: no-member-access"); } final AtomicBoolean wasReadCalled = new AtomicBoolean(false); @@ -85,9 +83,9 @@ public Object read(JsonReader in) throws IOException { ) .create(); - assertEquals("\"custom-write\"", gson.toJson(null, clazz)); - assertNull(gson.fromJson("{}", clazz)); - assertTrue(wasReadCalled.get()); + assertThat(gson.toJson(null, clazz)).isEqualTo("\"custom-write\""); + assertThat(gson.fromJson("{}", clazz)).isNull(); + assertThat(wasReadCalled.get()).isTrue(); } finally { System.setSecurityManager(original); } @@ -108,7 +106,7 @@ public Object read(JsonReader in) throws IOException { public void testSerializeInternalImplementationObject() { Gson gson = new Gson(); String json = gson.toJson(Collections.emptyList()); - assertEquals("[]", json); + assertThat(json).isEqualTo("[]"); // But deserialization should fail Class internalClass = Collections.emptyList().getClass(); @@ -118,10 +116,8 @@ public void testSerializeInternalImplementationObject() { } catch (JsonSyntaxException e) { fail("Unexpected exception; test has to be run with `--illegal-access=deny`"); } catch (JsonIOException expected) { - assertTrue(expected.getMessage().startsWith( - "Failed making constructor 'java.util.Collections$EmptyList()' accessible;" - + " either increase its visibility or write a custom InstanceCreator or TypeAdapter for its declaring type: " - )); + assertThat(expected).hasMessageThat().startsWith("Failed making constructor 'java.util.Collections$EmptyList()' accessible;" + + " either increase its visibility or write a custom InstanceCreator or TypeAdapter for its declaring type: "); } } } diff --git a/gson/src/test/java/com/google/gson/functional/ReusedTypeVariablesFullyResolveTest.java b/gson/src/test/java/com/google/gson/functional/ReusedTypeVariablesFullyResolveTest.java index 10c7c6db1d..f65113fc83 100644 --- a/gson/src/test/java/com/google/gson/functional/ReusedTypeVariablesFullyResolveTest.java +++ b/gson/src/test/java/com/google/gson/functional/ReusedTypeVariablesFullyResolveTest.java @@ -1,8 +1,6 @@ package com.google.gson.functional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static com.google.common.truth.Truth.assertThat; import com.google.gson.Gson; import com.google.gson.GsonBuilder; @@ -31,14 +29,14 @@ public void setUp() { public void testGenericsPreservation() { TestEnumSetCollection withSet = gson.fromJson("{\"collection\":[\"ONE\",\"THREE\"]}", TestEnumSetCollection.class); Iterator iterator = withSet.collection.iterator(); - assertNotNull(withSet); - assertNotNull(withSet.collection); - assertEquals(2, withSet.collection.size()); + assertThat(withSet).isNotNull(); + assertThat(withSet.collection).isNotNull(); + assertThat(withSet.collection).hasSize(2); TestEnum first = iterator.next(); TestEnum second = iterator.next(); - assertTrue(first instanceof TestEnum); - assertTrue(second instanceof TestEnum); + assertThat(first).isInstanceOf(TestEnum.class); + assertThat(second).isInstanceOf(TestEnum.class); } enum TestEnum { ONE, TWO, THREE } diff --git a/gson/src/test/java/com/google/gson/functional/RuntimeTypeAdapterFactoryFunctionalTest.java b/gson/src/test/java/com/google/gson/functional/RuntimeTypeAdapterFactoryFunctionalTest.java index c17cc54ae5..24f2044942 100644 --- a/gson/src/test/java/com/google/gson/functional/RuntimeTypeAdapterFactoryFunctionalTest.java +++ b/gson/src/test/java/com/google/gson/functional/RuntimeTypeAdapterFactoryFunctionalTest.java @@ -15,7 +15,7 @@ */ package com.google.gson.functional; -import static org.junit.Assert.assertEquals; +import static com.google.common.truth.Truth.assertThat; import com.google.gson.Gson; import com.google.gson.JsonElement; @@ -46,17 +46,17 @@ public final class RuntimeTypeAdapterFactoryFunctionalTest { * work correctly for {@link Gson#getDelegateAdapter(TypeAdapterFactory, TypeToken)}. */ @Test - public void testSubclassesAutomaticallySerialized() throws Exception { + public void testSubclassesAutomaticallySerialized() { Shape shape = new Circle(25); String json = gson.toJson(shape); shape = gson.fromJson(json, Shape.class); - assertEquals(25, ((Circle)shape).radius); + assertThat(((Circle)shape).radius).isEqualTo(25); shape = new Square(15); json = gson.toJson(shape); shape = gson.fromJson(json, Shape.class); - assertEquals(15, ((Square)shape).side); - assertEquals(ShapeType.SQUARE, shape.type); + assertThat(((Square)shape).side).isEqualTo(15); + assertThat(shape.type).isEqualTo(ShapeType.SQUARE); } @JsonAdapter(Shape.JsonAdapterFactory.class) @@ -161,7 +161,7 @@ public RuntimeTypeAdapterFactory registerSubtype(Class type) { } return new TypeAdapter() { - @Override public R read(JsonReader in) throws IOException { + @Override public R read(JsonReader in) { JsonElement jsonElement = Streams.parse(in); JsonElement labelJsonElement = jsonElement.getAsJsonObject().get(typeFieldName); if (labelJsonElement == null) { diff --git a/gson/src/test/java/com/google/gson/functional/SecurityTest.java b/gson/src/test/java/com/google/gson/functional/SecurityTest.java index 9e9272e1ad..33a7f4b379 100644 --- a/gson/src/test/java/com/google/gson/functional/SecurityTest.java +++ b/gson/src/test/java/com/google/gson/functional/SecurityTest.java @@ -16,8 +16,7 @@ package com.google.gson.functional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static com.google.common.truth.Truth.assertThat; import com.google.gson.Gson; import com.google.gson.GsonBuilder; @@ -47,7 +46,7 @@ public void setUp() throws Exception { public void testNonExecutableJsonSerialization() { Gson gson = gsonBuilder.generateNonExecutableJson().create(); String json = gson.toJson(new BagOfPrimitives()); - assertTrue(json.startsWith(JSON_NON_EXECUTABLE_PREFIX)); + assertThat(json.startsWith(JSON_NON_EXECUTABLE_PREFIX)).isTrue(); } @Test @@ -55,14 +54,14 @@ public void testNonExecutableJsonDeserialization() { String json = JSON_NON_EXECUTABLE_PREFIX + "{longValue:1}"; Gson gson = gsonBuilder.create(); BagOfPrimitives target = gson.fromJson(json, BagOfPrimitives.class); - assertEquals(1, target.longValue); + assertThat(target.longValue).isEqualTo(1); } @Test public void testJsonWithNonExectuableTokenSerialization() { Gson gson = gsonBuilder.generateNonExecutableJson().create(); String json = gson.toJson(JSON_NON_EXECUTABLE_PREFIX); - assertTrue(json.contains(")]}'\n")); + assertThat(json).contains(")]}'\n"); } /** @@ -74,7 +73,7 @@ public void testJsonWithNonExectuableTokenWithRegularGsonDeserialization() { Gson gson = gsonBuilder.create(); String json = JSON_NON_EXECUTABLE_PREFIX + "{stringValue:')]}\\u0027\\n'}"; BagOfPrimitives target = gson.fromJson(json, BagOfPrimitives.class); - assertEquals(")]}'\n", target.stringValue); + assertThat(target.stringValue).isEqualTo(")]}'\n"); } /** @@ -87,7 +86,7 @@ public void testJsonWithNonExectuableTokenWithConfiguredGsonDeserialization() { Gson gson = gsonBuilder.generateNonExecutableJson().create(); String json = JSON_NON_EXECUTABLE_PREFIX + "{intValue:2,stringValue:')]}\\u0027\\n'}"; BagOfPrimitives target = gson.fromJson(json, BagOfPrimitives.class); - assertEquals(")]}'\n", target.stringValue); - assertEquals(2, target.intValue); + assertThat(target.stringValue).isEqualTo(")]}'\n"); + assertThat(target.intValue).isEqualTo(2); } } diff --git a/gson/src/test/java/com/google/gson/functional/SerializedNameTest.java b/gson/src/test/java/com/google/gson/functional/SerializedNameTest.java index a1633700a5..32f2be1e37 100644 --- a/gson/src/test/java/com/google/gson/functional/SerializedNameTest.java +++ b/gson/src/test/java/com/google/gson/functional/SerializedNameTest.java @@ -15,7 +15,7 @@ */ package com.google.gson.functional; -import static org.junit.Assert.assertEquals; +import static com.google.common.truth.Truth.assertThat; import com.google.gson.Gson; import com.google.gson.annotations.SerializedName; @@ -28,23 +28,23 @@ public final class SerializedNameTest { public void testFirstNameIsChosenForSerialization() { MyClass target = new MyClass("v1", "v2"); // Ensure name1 occurs exactly once, and name2 and name3 don't appear - assertEquals("{\"name\":\"v1\",\"name1\":\"v2\"}", gson.toJson(target)); + assertThat(gson.toJson(target)).isEqualTo("{\"name\":\"v1\",\"name1\":\"v2\"}"); } @Test public void testMultipleNamesDeserializedCorrectly() { - assertEquals("v1", gson.fromJson("{'name':'v1'}", MyClass.class).a); + assertThat(gson.fromJson("{'name':'v1'}", MyClass.class).a).isEqualTo("v1"); // Both name1 and name2 gets deserialized to b - assertEquals("v11", gson.fromJson("{'name1':'v11'}", MyClass.class).b); - assertEquals("v2", gson.fromJson("{'name2':'v2'}", MyClass.class).b); - assertEquals("v3", gson.fromJson("{'name3':'v3'}", MyClass.class).b); + assertThat(gson.fromJson("{'name1':'v11'}", MyClass.class).b).isEqualTo("v11"); + assertThat(gson.fromJson("{'name2':'v2'}", MyClass.class).b).isEqualTo("v2"); + assertThat(gson.fromJson("{'name3':'v3'}", MyClass.class).b).isEqualTo("v3"); } @Test public void testMultipleNamesInTheSameString() { // The last value takes precedence - assertEquals("v3", gson.fromJson("{'name1':'v1','name2':'v2','name3':'v3'}", MyClass.class).b); + assertThat(gson.fromJson("{'name1':'v1','name2':'v2','name3':'v3'}", MyClass.class).b).isEqualTo("v3"); } private static final class MyClass { diff --git a/gson/src/test/java/com/google/gson/functional/StreamingTypeAdaptersTest.java b/gson/src/test/java/com/google/gson/functional/StreamingTypeAdaptersTest.java index ecd7dc35bd..f2e8653e5c 100644 --- a/gson/src/test/java/com/google/gson/functional/StreamingTypeAdaptersTest.java +++ b/gson/src/test/java/com/google/gson/functional/StreamingTypeAdaptersTest.java @@ -16,9 +16,8 @@ package com.google.gson.functional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static com.google.common.truth.Truth.assertThat; +import static com.google.common.truth.Truth.assertWithMessage; import static org.junit.Assert.fail; import com.google.gson.Gson; @@ -52,9 +51,9 @@ public void testSerialize() { truck.passengers = Arrays.asList(new Person("Jesse", 29), new Person("Jodie", 29)); truck.horsePower = 300; - assertEquals("{'horsePower':300.0," - + "'passengers':[{'age':29,'name':'Jesse'},{'age':29,'name':'Jodie'}]}", - truckAdapter.toJson(truck).replace('\"', '\'')); + assertThat(truckAdapter.toJson(truck).replace('\"', '\'')) + .isEqualTo("{'horsePower':300.0," + + "'passengers':[{'age':29,'name':'Jesse'},{'age':29,'name':'Jodie'}]}"); } @Test @@ -62,36 +61,37 @@ public void testDeserialize() throws IOException { String json = "{'horsePower':300.0," + "'passengers':[{'age':29,'name':'Jesse'},{'age':29,'name':'Jodie'}]}"; Truck truck = truckAdapter.fromJson(json.replace('\'', '\"')); - assertEquals(300.0, truck.horsePower, 0); - assertEquals(Arrays.asList(new Person("Jesse", 29), new Person("Jodie", 29)), truck.passengers); + assertThat(truck.horsePower).isEqualTo(300.0); + assertThat(truck.passengers) + .isEqualTo(Arrays.asList(new Person("Jesse", 29), new Person("Jodie", 29))); } @Test public void testSerializeNullField() { Truck truck = new Truck(); truck.passengers = null; - assertEquals("{'horsePower':0.0,'passengers':null}", - truckAdapter.toJson(truck).replace('\"', '\'')); + assertThat(truckAdapter.toJson(truck).replace('\"', '\'')) + .isEqualTo("{'horsePower':0.0,'passengers':null}"); } @Test public void testDeserializeNullField() throws IOException { Truck truck = truckAdapter.fromJson("{'horsePower':0.0,'passengers':null}".replace('\'', '\"')); - assertNull(truck.passengers); + assertThat(truck.passengers).isNull(); } @Test public void testSerializeNullObject() { Truck truck = new Truck(); truck.passengers = Arrays.asList((Person) null); - assertEquals("{'horsePower':0.0,'passengers':[null]}", - truckAdapter.toJson(truck).replace('\"', '\'')); + assertThat(truckAdapter.toJson(truck).replace('\"', '\'')) + .isEqualTo("{'horsePower':0.0,'passengers':[null]}"); } @Test public void testDeserializeNullObject() throws IOException { Truck truck = truckAdapter.fromJson("{'horsePower':0.0,'passengers':[null]}".replace('\'', '\"')); - assertEquals(Arrays.asList((Person) null), truck.passengers); + assertThat(truck.passengers).isEqualTo(Arrays.asList((Person) null)); } @Test @@ -99,15 +99,15 @@ public void testSerializeWithCustomTypeAdapter() { usePersonNameAdapter(); Truck truck = new Truck(); truck.passengers = Arrays.asList(new Person("Jesse", 29), new Person("Jodie", 29)); - assertEquals("{'horsePower':0.0,'passengers':['Jesse','Jodie']}", - truckAdapter.toJson(truck).replace('\"', '\'')); + assertThat(truckAdapter.toJson(truck).replace('\"', '\'')) + .isEqualTo("{'horsePower':0.0,'passengers':['Jesse','Jodie']}"); } @Test public void testDeserializeWithCustomTypeAdapter() throws IOException { usePersonNameAdapter(); Truck truck = truckAdapter.fromJson("{'horsePower':0.0,'passengers':['Jesse','Jodie']}".replace('\'', '\"')); - assertEquals(Arrays.asList(new Person("Jesse", -1), new Person("Jodie", -1)), truck.passengers); + assertThat(truck.passengers).isEqualTo(Arrays.asList(new Person("Jesse", -1), new Person("Jodie", -1))); } private void usePersonNameAdapter() { @@ -129,7 +129,7 @@ public void testSerializeMap() { Map map = new LinkedHashMap<>(); map.put("a", 5.0); map.put("b", 10.0); - assertEquals("{'a':5.0,'b':10.0}", mapAdapter.toJson(map).replace('"', '\'')); + assertThat(mapAdapter.toJson(map).replace('"', '\'')).isEqualTo("{'a':5.0,'b':10.0}"); } @Test @@ -137,27 +137,27 @@ public void testDeserializeMap() throws IOException { Map map = new LinkedHashMap<>(); map.put("a", 5.0); map.put("b", 10.0); - assertEquals(map, mapAdapter.fromJson("{'a':5.0,'b':10.0}".replace('\'', '\"'))); + assertThat(mapAdapter.fromJson("{'a':5.0,'b':10.0}".replace('\'', '\"'))).isEqualTo(map); } @Test public void testSerialize1dArray() { TypeAdapter arrayAdapter = miniGson.getAdapter(new TypeToken() {}); - assertEquals("[1.0,2.0,3.0]", arrayAdapter.toJson(new double[]{ 1.0, 2.0, 3.0 })); + assertThat(arrayAdapter.toJson(new double[]{ 1.0, 2.0, 3.0 })).isEqualTo("[1.0,2.0,3.0]"); } @Test public void testDeserialize1dArray() throws IOException { TypeAdapter arrayAdapter = miniGson.getAdapter(new TypeToken() {}); double[] array = arrayAdapter.fromJson("[1.0,2.0,3.0]"); - assertTrue(Arrays.toString(array), Arrays.equals(new double[]{1.0, 2.0, 3.0}, array)); + assertWithMessage(Arrays.toString(array)).that(Arrays.equals(new double[]{1.0, 2.0, 3.0}, array)).isTrue(); } @Test public void testSerialize2dArray() { TypeAdapter arrayAdapter = miniGson.getAdapter(new TypeToken() {}); double[][] array = { {1.0, 2.0 }, { 3.0 } }; - assertEquals("[[1.0,2.0],[3.0]]", arrayAdapter.toJson(array)); + assertThat(arrayAdapter.toJson(array)).isEqualTo("[[1.0,2.0],[3.0]]"); } @Test @@ -165,7 +165,7 @@ public void testDeserialize2dArray() throws IOException { TypeAdapter arrayAdapter = miniGson.getAdapter(new TypeToken() {}); double[][] array = arrayAdapter.fromJson("[[1.0,2.0],[3.0]]"); double[][] expected = { {1.0, 2.0 }, { 3.0 } }; - assertTrue(Arrays.toString(array), Arrays.deepEquals(expected, array)); + assertWithMessage(Arrays.toString(array)).that(Arrays.deepEquals(expected, array)).isTrue(); } @Test @@ -196,12 +196,12 @@ public void testNullSafe() { fail(); } catch (JsonSyntaxException expected) {} gson = new GsonBuilder().registerTypeAdapter(Person.class, typeAdapter.nullSafe()).create(); - assertEquals("{\"horsePower\":1.0,\"passengers\":[null,\"jesse,30\"]}", - gson.toJson(truck, Truck.class)); + assertThat(gson.toJson(truck, Truck.class)) + .isEqualTo("{\"horsePower\":1.0,\"passengers\":[null,\"jesse,30\"]}"); truck = gson.fromJson(json, Truck.class); - assertEquals(1.0D, truck.horsePower, 0); - assertNull(truck.passengers.get(0)); - assertEquals("jesse", truck.passengers.get(1).name); + assertThat(truck.horsePower).isEqualTo(1.0D); + assertThat(truck.passengers.get(0)).isNull(); + assertThat(truck.passengers.get(1).name).isEqualTo("jesse"); } @Test @@ -210,10 +210,10 @@ public void testSerializeRecursive() { Node root = new Node("root"); root.left = new Node("left"); root.right = new Node("right"); - assertEquals("{'label':'root'," - + "'left':{'label':'left','left':null,'right':null}," - + "'right':{'label':'right','left':null,'right':null}}", - nodeAdapter.toJson(root).replace('"', '\'')); + assertThat(nodeAdapter.toJson(root).replace('"', '\'')) + .isEqualTo("{'label':'root'," + + "'left':{'label':'left','left':null,'right':null}," + + "'right':{'label':'right','left':null,'right':null}}"); } @Test @@ -228,8 +228,8 @@ public void testFromJsonTree() { truckObject.add("passengers", passengersArray); Truck truck = truckAdapter.fromJsonTree(truckObject); - assertEquals(300.0, truck.horsePower, 0); - assertEquals(Arrays.asList(new Person("Jesse", 30)), truck.passengers); + assertThat(truck.horsePower).isEqualTo(300.0); + assertThat(truck.passengers).isEqualTo(List.of(new Person("Jesse", 30))); } static class Truck { diff --git a/gson/src/test/java/com/google/gson/functional/StringTest.java b/gson/src/test/java/com/google/gson/functional/StringTest.java index 80c7383145..b66a01c535 100644 --- a/gson/src/test/java/com/google/gson/functional/StringTest.java +++ b/gson/src/test/java/com/google/gson/functional/StringTest.java @@ -1,6 +1,6 @@ package com.google.gson.functional; -import static org.junit.Assert.assertEquals; +import static com.google.common.truth.Truth.assertThat; import com.google.gson.Gson; import org.junit.Before; @@ -21,94 +21,94 @@ public void setUp() throws Exception { } @Test - public void testStringValueSerialization() throws Exception { + public void testStringValueSerialization() { String value = "someRandomStringValue"; - assertEquals('"' + value + '"', gson.toJson(value)); + assertThat(gson.toJson(value)).isEqualTo('"' + value + '"'); } @Test - public void testStringValueDeserialization() throws Exception { + public void testStringValueDeserialization() { String value = "someRandomStringValue"; String actual = gson.fromJson("\"" + value + "\"", String.class); - assertEquals(value, actual); + assertThat(actual).isEqualTo(value); } @Test - public void testSingleQuoteInStringSerialization() throws Exception { + public void testSingleQuoteInStringSerialization() { String valueWithQuotes = "beforeQuote'afterQuote"; String jsonRepresentation = gson.toJson(valueWithQuotes); - assertEquals(valueWithQuotes, gson.fromJson(jsonRepresentation, String.class)); + assertThat(gson.fromJson(jsonRepresentation, String.class)).isEqualTo(valueWithQuotes); } @Test - public void testEscapedCtrlNInStringSerialization() throws Exception { + public void testEscapedCtrlNInStringSerialization() { String value = "a\nb"; String json = gson.toJson(value); - assertEquals("\"a\\nb\"", json); + assertThat(json).isEqualTo("\"a\\nb\""); } @Test - public void testEscapedCtrlNInStringDeserialization() throws Exception { + public void testEscapedCtrlNInStringDeserialization() { String json = "'a\\nb'"; String actual = gson.fromJson(json, String.class); - assertEquals("a\nb", actual); + assertThat(actual).isEqualTo("a\nb"); } @Test - public void testEscapedCtrlRInStringSerialization() throws Exception { + public void testEscapedCtrlRInStringSerialization() { String value = "a\rb"; String json = gson.toJson(value); - assertEquals("\"a\\rb\"", json); + assertThat(json).isEqualTo("\"a\\rb\""); } @Test - public void testEscapedCtrlRInStringDeserialization() throws Exception { + public void testEscapedCtrlRInStringDeserialization() { String json = "'a\\rb'"; String actual = gson.fromJson(json, String.class); - assertEquals("a\rb", actual); + assertThat(actual).isEqualTo("a\rb"); } @Test - public void testEscapedBackslashInStringSerialization() throws Exception { + public void testEscapedBackslashInStringSerialization() { String value = "a\\b"; String json = gson.toJson(value); - assertEquals("\"a\\\\b\"", json); + assertThat(json).isEqualTo("\"a\\\\b\""); } @Test - public void testEscapedBackslashInStringDeserialization() throws Exception { + public void testEscapedBackslashInStringDeserialization() { String actual = gson.fromJson("'a\\\\b'", String.class); - assertEquals("a\\b", actual); + assertThat(actual).isEqualTo("a\\b"); } @Test - public void testSingleQuoteInStringDeserialization() throws Exception { + public void testSingleQuoteInStringDeserialization() { String value = "beforeQuote'afterQuote"; String actual = gson.fromJson("\"" + value + "\"", String.class); - assertEquals(value, actual); + assertThat(actual).isEqualTo(value); } @Test - public void testEscapingQuotesInStringSerialization() throws Exception { + public void testEscapingQuotesInStringSerialization() { String valueWithQuotes = "beforeQuote\"afterQuote"; String jsonRepresentation = gson.toJson(valueWithQuotes); String target = gson.fromJson(jsonRepresentation, String.class); - assertEquals(valueWithQuotes, target); + assertThat(target).isEqualTo(valueWithQuotes); } @Test - public void testEscapingQuotesInStringDeserialization() throws Exception { + public void testEscapingQuotesInStringDeserialization() { String value = "beforeQuote\\\"afterQuote"; String actual = gson.fromJson("\"" + value + "\"", String.class); String expected = "beforeQuote\"afterQuote"; - assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); } @Test - public void testStringValueAsSingleElementArraySerialization() throws Exception { + public void testStringValueAsSingleElementArraySerialization() { String[] target = {"abc"}; - assertEquals("[\"abc\"]", gson.toJson(target)); - assertEquals("[\"abc\"]", gson.toJson(target, String[].class)); + assertThat(gson.toJson(target)).isEqualTo("[\"abc\"]"); + assertThat(gson.toJson(target, String[].class)).isEqualTo("[\"abc\"]"); } @Test @@ -116,7 +116,7 @@ public void testStringWithEscapedSlashDeserialization() { String value = "/"; String json = "'\\/'"; String actual = gson.fromJson(json, String.class); - assertEquals(value, actual); + assertThat(actual).isEqualTo(value); } /** @@ -126,7 +126,7 @@ public void testStringWithEscapedSlashDeserialization() { public void testAssignmentCharSerialization() { String value = "abc="; String json = gson.toJson(value); - assertEquals("\"abc\\u003d\"", json); + assertThat(json).isEqualTo("\"abc\\u003d\""); } /** @@ -136,24 +136,24 @@ public void testAssignmentCharSerialization() { public void testAssignmentCharDeserialization() { String json = "\"abc=\""; String value = gson.fromJson(json, String.class); - assertEquals("abc=", value); + assertThat(value).isEqualTo("abc="); json = "'abc\u003d'"; value = gson.fromJson(json, String.class); - assertEquals("abc=", value); + assertThat(value).isEqualTo("abc="); } @Test public void testJavascriptKeywordsInStringSerialization() { String value = "null true false function"; String json = gson.toJson(value); - assertEquals("\"" + value + "\"", json); + assertThat(json).isEqualTo("\"" + value + "\""); } @Test public void testJavascriptKeywordsInStringDeserialization() { String json = "'null true false function'"; String value = gson.fromJson(json, String.class); - assertEquals(json.substring(1, json.length() - 1), value); + assertThat(json.substring(1, json.length() - 1)).isEqualTo(value); } } diff --git a/gson/src/test/java/com/google/gson/functional/ToNumberPolicyFunctionalTest.java b/gson/src/test/java/com/google/gson/functional/ToNumberPolicyFunctionalTest.java index 1e7728364f..d500546fca 100644 --- a/gson/src/test/java/com/google/gson/functional/ToNumberPolicyFunctionalTest.java +++ b/gson/src/test/java/com/google/gson/functional/ToNumberPolicyFunctionalTest.java @@ -16,7 +16,7 @@ package com.google.gson.functional; -import static org.junit.Assert.assertEquals; +import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.fail; import com.google.gson.Gson; @@ -28,7 +28,6 @@ import com.google.gson.stream.JsonReader; import java.lang.reflect.Type; import java.math.BigDecimal; -import java.util.Arrays; import java.util.Collection; import java.util.LinkedList; import java.util.List; @@ -38,10 +37,10 @@ public class ToNumberPolicyFunctionalTest { @Test public void testDefault() { Gson gson = new Gson(); - assertEquals(null, gson.fromJson("null", Object.class)); - assertEquals(10D, gson.fromJson("10", Object.class)); - assertEquals(null, gson.fromJson("null", Number.class)); - assertEquals(new LazilyParsedNumber("10"), gson.fromJson("10", Number.class)); + assertThat(gson.fromJson("null", Object.class)).isEqualTo(null); + assertThat(gson.fromJson("10", Object.class)).isEqualTo(10D); + assertThat(gson.fromJson("null", Number.class)).isEqualTo(null); + assertThat(gson.fromJson("10", Number.class)).isEqualTo(new LazilyParsedNumber("10")); } @Test @@ -50,10 +49,10 @@ public void testAsDoubles() { .setObjectToNumberStrategy(ToNumberPolicy.DOUBLE) .setNumberToNumberStrategy(ToNumberPolicy.DOUBLE) .create(); - assertEquals(null, gson.fromJson("null", Object.class)); - assertEquals(10.0, gson.fromJson("10", Object.class)); - assertEquals(null, gson.fromJson("null", Number.class)); - assertEquals(10.0, gson.fromJson("10", Number.class)); + assertThat(gson.fromJson("null", Object.class)).isEqualTo(null); + assertThat(gson.fromJson("10", Object.class)).isEqualTo(10.0); + assertThat(gson.fromJson("null", Number.class)).isEqualTo(null); + assertThat(gson.fromJson("10", Number.class)).isEqualTo(10.0); } @Test @@ -62,10 +61,10 @@ public void testAsLazilyParsedNumbers() { .setObjectToNumberStrategy(ToNumberPolicy.LAZILY_PARSED_NUMBER) .setNumberToNumberStrategy(ToNumberPolicy.LAZILY_PARSED_NUMBER) .create(); - assertEquals(null, gson.fromJson("null", Object.class)); - assertEquals(new LazilyParsedNumber("10"), gson.fromJson("10", Object.class)); - assertEquals(null, gson.fromJson("null", Number.class)); - assertEquals(new LazilyParsedNumber("10"), gson.fromJson("10", Number.class)); + assertThat(gson.fromJson("null", Object.class)).isEqualTo(null); + assertThat(gson.fromJson("10", Object.class)).isEqualTo(new LazilyParsedNumber("10")); + assertThat(gson.fromJson("null", Number.class)).isEqualTo(null); + assertThat(gson.fromJson("10", Number.class)).isEqualTo(new LazilyParsedNumber("10")); } @Test @@ -74,12 +73,12 @@ public void testAsLongsOrDoubles() { .setObjectToNumberStrategy(ToNumberPolicy.LONG_OR_DOUBLE) .setNumberToNumberStrategy(ToNumberPolicy.LONG_OR_DOUBLE) .create(); - assertEquals(null, gson.fromJson("null", Object.class)); - assertEquals(10L, gson.fromJson("10", Object.class)); - assertEquals(10.0, gson.fromJson("10.0", Object.class)); - assertEquals(null, gson.fromJson("null", Number.class)); - assertEquals(10L, gson.fromJson("10", Number.class)); - assertEquals(10.0, gson.fromJson("10.0", Number.class)); + assertThat(gson.fromJson("null", Object.class)).isEqualTo(null); + assertThat(gson.fromJson("10", Object.class)).isEqualTo(10L); + assertThat(gson.fromJson("10.0", Object.class)).isEqualTo(10.0); + assertThat(gson.fromJson("null", Number.class)).isEqualTo(null); + assertThat(gson.fromJson("10", Number.class)).isEqualTo(10L); + assertThat(gson.fromJson("10.0", Number.class)).isEqualTo(10.0); } @Test @@ -88,14 +87,14 @@ public void testAsBigDecimals() { .setObjectToNumberStrategy(ToNumberPolicy.BIG_DECIMAL) .setNumberToNumberStrategy(ToNumberPolicy.BIG_DECIMAL) .create(); - assertEquals(null, gson.fromJson("null", Object.class)); - assertEquals(new BigDecimal("10"), gson.fromJson("10", Object.class)); - assertEquals(new BigDecimal("10.0"), gson.fromJson("10.0", Object.class)); - assertEquals(null, gson.fromJson("null", Number.class)); - assertEquals(new BigDecimal("10"), gson.fromJson("10", Number.class)); - assertEquals(new BigDecimal("10.0"), gson.fromJson("10.0", Number.class)); - assertEquals(new BigDecimal("3.141592653589793238462643383279"), gson.fromJson("3.141592653589793238462643383279", BigDecimal.class)); - assertEquals(new BigDecimal("1e400"), gson.fromJson("1e400", BigDecimal.class)); + assertThat(gson.fromJson("null", Object.class)).isEqualTo(null); + assertThat(gson.fromJson("10", Object.class)).isEqualTo(new BigDecimal("10")); + assertThat(gson.fromJson("10.0", Object.class)).isEqualTo(new BigDecimal("10.0")); + assertThat(gson.fromJson("null", Number.class)).isEqualTo(null); + assertThat(gson.fromJson("10", Number.class)).isEqualTo(new BigDecimal("10")); + assertThat(gson.fromJson("10.0", Number.class)).isEqualTo(new BigDecimal("10.0")); + assertThat(gson.fromJson("3.141592653589793238462643383279", BigDecimal.class)).isEqualTo(new BigDecimal("3.141592653589793238462643383279")); + assertThat(gson.fromJson("1e400", BigDecimal.class)).isEqualTo(new BigDecimal("1e400")); } @Test @@ -110,10 +109,10 @@ public void testAsListOfLongsOrDoubles() { expected.add(10.0); Type objectCollectionType = new TypeToken>() { }.getType(); Collection objects = gson.fromJson("[null,10,10.0]", objectCollectionType); - assertEquals(expected, objects); + assertThat(objects).isEqualTo(expected); Type numberCollectionType = new TypeToken>() { }.getType(); Collection numbers = gson.fromJson("[null,10,10.0]", numberCollectionType); - assertEquals(expected, numbers); + assertThat(numbers).isEqualTo(expected); } @Test @@ -129,7 +128,7 @@ public Byte readNumber(JsonReader in) { .setNumberToNumberStrategy(fail) .create(); List numbers = gson.fromJson("[null, 10, 20, 30]", new TypeToken>() {}.getType()); - assertEquals(Arrays.asList(null, (byte) 10, (byte) 20, (byte) 30), numbers); + assertThat(numbers).containsExactly(null, (byte) 10, (byte) 20, (byte) 30).inOrder(); try { gson.fromJson("[null, 10, 20, 30]", new TypeToken>() {}.getType()); fail(); diff --git a/gson/src/test/java/com/google/gson/functional/TreeTypeAdaptersTest.java b/gson/src/test/java/com/google/gson/functional/TreeTypeAdaptersTest.java index be079af035..9e0382d010 100644 --- a/gson/src/test/java/com/google/gson/functional/TreeTypeAdaptersTest.java +++ b/gson/src/test/java/com/google/gson/functional/TreeTypeAdaptersTest.java @@ -16,8 +16,7 @@ package com.google.gson.functional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static com.google.common.truth.Truth.assertThat; import com.google.gson.Gson; import com.google.gson.GsonBuilder; @@ -65,9 +64,9 @@ public void setUp() { @Test public void testSerializeId() { String json = gson.toJson(course, TYPE_COURSE_HISTORY); - assertTrue(json.contains(String.valueOf(COURSE_ID.getValue()))); - assertTrue(json.contains(String.valueOf(STUDENT1_ID.getValue()))); - assertTrue(json.contains(String.valueOf(STUDENT2_ID.getValue()))); + assertThat(json).contains(String.valueOf(COURSE_ID.getValue())); + assertThat(json).contains(String.valueOf(STUDENT1_ID.getValue())); + assertThat(json).contains(String.valueOf(STUDENT2_ID.getValue())); } @Test @@ -75,9 +74,9 @@ public void testDeserializeId() { String json = "{courseId:1,students:[{id:1,name:'first'},{id:6,name:'second'}]," + "numAssignments:4,assignment:{}}"; Course target = gson.fromJson(json, TYPE_COURSE_HISTORY); - assertEquals("1", target.getStudents().get(0).id.getValue()); - assertEquals("6", target.getStudents().get(1).id.getValue()); - assertEquals("1", target.getId().getValue()); + assertThat(target.getStudents().get(0).id.getValue()).isEqualTo("1"); + assertThat(target.getStudents().get(1).id.getValue()).isEqualTo("6"); + assertThat(target.getId().getValue()).isEqualTo("1"); } private static final class Id { diff --git a/gson/src/test/java/com/google/gson/functional/TypeAdapterPrecedenceTest.java b/gson/src/test/java/com/google/gson/functional/TypeAdapterPrecedenceTest.java index 28120bf3f9..e96175a3c9 100644 --- a/gson/src/test/java/com/google/gson/functional/TypeAdapterPrecedenceTest.java +++ b/gson/src/test/java/com/google/gson/functional/TypeAdapterPrecedenceTest.java @@ -16,7 +16,7 @@ package com.google.gson.functional; -import static org.junit.Assert.assertEquals; +import static com.google.common.truth.Truth.assertThat; import com.google.gson.Gson; import com.google.gson.GsonBuilder; @@ -42,8 +42,8 @@ public void testNonstreamingFollowedByNonstreaming() { .registerTypeAdapter(Foo.class, newDeserializer("deserializer 1")) .registerTypeAdapter(Foo.class, newDeserializer("deserializer 2")) .create(); - assertEquals("\"foo via serializer 2\"", gson.toJson(new Foo("foo"))); - assertEquals("foo via deserializer 2", gson.fromJson("foo", Foo.class).name); + assertThat(gson.toJson(new Foo("foo"))).isEqualTo("\"foo via serializer 2\""); + assertThat(gson.fromJson("foo", Foo.class).name).isEqualTo("foo via deserializer 2"); } @Test @@ -52,8 +52,8 @@ public void testStreamingFollowedByStreaming() { .registerTypeAdapter(Foo.class, newTypeAdapter("type adapter 1")) .registerTypeAdapter(Foo.class, newTypeAdapter("type adapter 2")) .create(); - assertEquals("\"foo via type adapter 2\"", gson.toJson(new Foo("foo"))); - assertEquals("foo via type adapter 2", gson.fromJson("foo", Foo.class).name); + assertThat(gson.toJson(new Foo("foo"))).isEqualTo("\"foo via type adapter 2\""); + assertThat(gson.fromJson("foo", Foo.class).name).isEqualTo("foo via type adapter 2"); } @Test @@ -63,8 +63,8 @@ public void testSerializeNonstreamingTypeAdapterFollowedByStreamingTypeAdapter() .registerTypeAdapter(Foo.class, newDeserializer("deserializer")) .registerTypeAdapter(Foo.class, newTypeAdapter("type adapter")) .create(); - assertEquals("\"foo via type adapter\"", gson.toJson(new Foo("foo"))); - assertEquals("foo via type adapter", gson.fromJson("foo", Foo.class).name); + assertThat(gson.toJson(new Foo("foo"))).isEqualTo("\"foo via type adapter\""); + assertThat(gson.fromJson("foo", Foo.class).name).isEqualTo("foo via type adapter"); } @Test @@ -74,8 +74,8 @@ public void testStreamingFollowedByNonstreaming() { .registerTypeAdapter(Foo.class, newSerializer("serializer")) .registerTypeAdapter(Foo.class, newDeserializer("deserializer")) .create(); - assertEquals("\"foo via serializer\"", gson.toJson(new Foo("foo"))); - assertEquals("foo via deserializer", gson.fromJson("foo", Foo.class).name); + assertThat(gson.toJson(new Foo("foo"))).isEqualTo("\"foo via serializer\""); + assertThat( gson.fromJson("foo", Foo.class).name).isEqualTo("foo via deserializer"); } @Test @@ -85,8 +85,8 @@ public void testStreamingHierarchicalFollowedByNonstreaming() { .registerTypeAdapter(Foo.class, newSerializer("serializer")) .registerTypeAdapter(Foo.class, newDeserializer("deserializer")) .create(); - assertEquals("\"foo via serializer\"", gson.toJson(new Foo("foo"))); - assertEquals("foo via deserializer", gson.fromJson("foo", Foo.class).name); + assertThat(gson.toJson(new Foo("foo"))).isEqualTo("\"foo via serializer\""); + assertThat(gson.fromJson("foo", Foo.class).name).isEqualTo("foo via deserializer"); } @Test @@ -96,8 +96,8 @@ public void testStreamingFollowedByNonstreamingHierarchical() { .registerTypeHierarchyAdapter(Foo.class, newSerializer("serializer")) .registerTypeHierarchyAdapter(Foo.class, newDeserializer("deserializer")) .create(); - assertEquals("\"foo via type adapter\"", gson.toJson(new Foo("foo"))); - assertEquals("foo via type adapter", gson.fromJson("foo", Foo.class).name); + assertThat(gson.toJson(new Foo("foo"))).isEqualTo("\"foo via type adapter\""); + assertThat(gson.fromJson("foo", Foo.class).name).isEqualTo("foo via type adapter"); } @Test @@ -107,8 +107,8 @@ public void testStreamingHierarchicalFollowedByNonstreamingHierarchical() { .registerTypeHierarchyAdapter(Foo.class, newDeserializer("deserializer")) .registerTypeHierarchyAdapter(Foo.class, newTypeAdapter("type adapter")) .create(); - assertEquals("\"foo via type adapter\"", gson.toJson(new Foo("foo"))); - assertEquals("foo via type adapter", gson.fromJson("foo", Foo.class).name); + assertThat(gson.toJson(new Foo("foo"))).isEqualTo("\"foo via type adapter\""); + assertThat(gson.fromJson("foo", Foo.class).name).isEqualTo("foo via type adapter"); } @Test @@ -119,8 +119,8 @@ public void testNonstreamingHierarchicalFollowedByNonstreaming() { .registerTypeAdapter(Foo.class, newSerializer("non hierarchical")) .registerTypeAdapter(Foo.class, newDeserializer("non hierarchical")) .create(); - assertEquals("\"foo via non hierarchical\"", gson.toJson(new Foo("foo"))); - assertEquals("foo via non hierarchical", gson.fromJson("foo", Foo.class).name); + assertThat(gson.toJson(new Foo("foo"))).isEqualTo("\"foo via non hierarchical\""); + assertThat(gson.fromJson("foo", Foo.class).name).isEqualTo("foo via non hierarchical"); } private static class Foo { diff --git a/gson/src/test/java/com/google/gson/functional/TypeAdapterRuntimeTypeWrapperTest.java b/gson/src/test/java/com/google/gson/functional/TypeAdapterRuntimeTypeWrapperTest.java index 73a0101243..d7551135c2 100644 --- a/gson/src/test/java/com/google/gson/functional/TypeAdapterRuntimeTypeWrapperTest.java +++ b/gson/src/test/java/com/google/gson/functional/TypeAdapterRuntimeTypeWrapperTest.java @@ -1,6 +1,6 @@ package com.google.gson.functional; -import static org.junit.Assert.assertEquals; +import static com.google.common.truth.Truth.assertThat; import com.google.gson.Gson; import com.google.gson.GsonBuilder; @@ -51,7 +51,7 @@ public JsonElement serialize(Base src, Type typeOfSrc, JsonSerializationContext .create(); String json = gson.toJson(new Container()); - assertEquals("{\"b\":\"serializer\"}", json); + assertThat(json).isEqualTo("{\"b\":\"serializer\"}"); } /** @@ -66,7 +66,7 @@ public void testJsonDeserializer_ReflectiveSerializerDelegate() { .create(); String json = gson.toJson(new Container()); - assertEquals("{\"b\":{\"f\":\"test\"}}", json); + assertThat(json).isEqualTo("{\"b\":{\"f\":\"test\"}}"); } /** @@ -92,7 +92,7 @@ public void write(JsonWriter out, Base value) throws IOException { .create(); String json = gson.toJson(new Container()); - assertEquals("{\"b\":\"custom delegate\"}", json); + assertThat(json).isEqualTo("{\"b\":\"custom delegate\"}"); } /** @@ -109,7 +109,7 @@ public void testJsonDeserializer_ReflectiveTreeSerializerDelegate() { .create(); String json = gson.toJson(new Container()); - assertEquals("{\"b\":{\"f\":\"test\"}}", json); + assertThat(json).isEqualTo("{\"b\":{\"f\":\"test\"}}"); } /** @@ -131,7 +131,7 @@ public JsonElement serialize(Base src, Type typeOfSrc, JsonSerializationContext .create(); String json = gson.toJson(new Container()); - assertEquals("{\"b\":\"custom delegate\"}", json); + assertThat(json).isEqualTo("{\"b\":\"custom delegate\"}"); } /** @@ -160,7 +160,7 @@ public JsonElement serialize(Base src, Type typeOfSrc, JsonSerializationContext .create(); String json = gson.toJson(new Container()); - assertEquals("{\"b\":{\"f\":\"test\"}}", json); + assertThat(json).isEqualTo("{\"b\":{\"f\":\"test\"}}"); } private static class CyclicBase { @@ -188,6 +188,6 @@ public void testGsonFutureAdapter() { CyclicBase b = new CyclicBase(); b.f = new CyclicSub(2); String json = new Gson().toJson(b); - assertEquals("{\"f\":{\"i\":2}}", json); + assertThat(json).isEqualTo("{\"f\":{\"i\":2}}"); } } diff --git a/gson/src/test/java/com/google/gson/functional/TypeHierarchyAdapterTest.java b/gson/src/test/java/com/google/gson/functional/TypeHierarchyAdapterTest.java index e43fa5f7f4..0804bcfdd1 100644 --- a/gson/src/test/java/com/google/gson/functional/TypeHierarchyAdapterTest.java +++ b/gson/src/test/java/com/google/gson/functional/TypeHierarchyAdapterTest.java @@ -16,7 +16,7 @@ package com.google.gson.functional; -import static org.junit.Assert.assertEquals; +import static com.google.common.truth.Truth.assertThat; import com.google.gson.Gson; import com.google.gson.GsonBuilder; @@ -67,7 +67,7 @@ public void testTypeHierarchy() { company.ceo = eric; String json = gson.toJson(company, Company.class); - assertEquals("{\n" + + assertThat(json).isEqualTo("{\n" + " \"ceo\": {\n" + " \"userid\": \"eric\",\n" + " \"startDate\": 2001,\n" + @@ -104,19 +104,17 @@ public void testTypeHierarchy() { " \"startDate\": 2006\n" + " }\n" + " }\n" + - "}", json); + "}"); Company copied = gson.fromJson(json, Company.class); - assertEquals(json, gson.toJson(copied, Company.class)); - assertEquals(copied.ceo.userid, company.ceo.userid); - assertEquals(copied.ceo.assistant.userid, company.ceo.assistant.userid); - assertEquals(copied.ceo.minions[0].userid, company.ceo.minions[0].userid); - assertEquals(copied.ceo.minions[1].userid, company.ceo.minions[1].userid); - assertEquals(copied.ceo.minions[2].userid, company.ceo.minions[2].userid); - assertEquals(((Manager) copied.ceo.minions[2]).minions[0].userid, - ((Manager) company.ceo.minions[2]).minions[0].userid); - assertEquals(((Manager) copied.ceo.minions[2]).minions[1].userid, - ((Manager) company.ceo.minions[2]).minions[1].userid); + assertThat(gson.toJson(copied, Company.class)).isEqualTo(json); + assertThat(company.ceo.userid).isEqualTo(copied.ceo.userid); + assertThat(company.ceo.assistant.userid).isEqualTo(copied.ceo.assistant.userid); + assertThat(company.ceo.minions[0].userid).isEqualTo(copied.ceo.minions[0].userid); + assertThat(company.ceo.minions[1].userid).isEqualTo(copied.ceo.minions[1].userid); + assertThat(company.ceo.minions[2].userid).isEqualTo(copied.ceo.minions[2].userid); + assertThat(((Manager) company.ceo.minions[2]).minions[0].userid).isEqualTo(((Manager) copied.ceo.minions[2]).minions[0].userid); + assertThat(((Manager) company.ceo.minions[2]).minions[1].userid).isEqualTo(((Manager) copied.ceo.minions[2]).minions[1].userid); } @Test @@ -130,9 +128,9 @@ public void testRegisterSuperTypeFirst() { manager.userid = "inder"; String json = gson.toJson(manager, Manager.class); - assertEquals("\"inder\"", json); + assertThat(json).isEqualTo("\"inder\""); Manager copied = gson.fromJson(json, Manager.class); - assertEquals(manager.userid, copied.userid); + assertThat(copied.userid).isEqualTo(manager.userid); } /** This behaviour changed in Gson 2.1; it used to throw. */ diff --git a/gson/src/test/java/com/google/gson/functional/TypeVariableTest.java b/gson/src/test/java/com/google/gson/functional/TypeVariableTest.java index 88b2d19d8e..fdde72c892 100644 --- a/gson/src/test/java/com/google/gson/functional/TypeVariableTest.java +++ b/gson/src/test/java/com/google/gson/functional/TypeVariableTest.java @@ -15,7 +15,7 @@ */ package com.google.gson.functional; -import static org.junit.Assert.assertEquals; +import static com.google.common.truth.Truth.assertThat; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; @@ -36,7 +36,7 @@ public class TypeVariableTest { @Test - public void testAdvancedTypeVariables() throws Exception { + public void testAdvancedTypeVariables() { Gson gson = new Gson(); Bar bar1 = new Bar("someString", 1, true); ArrayList arrayList = new ArrayList<>(); @@ -48,29 +48,29 @@ public void testAdvancedTypeVariables() throws Exception { String json = gson.toJson(bar1); Bar bar2 = gson.fromJson(json, Bar.class); - assertEquals(bar1, bar2); + assertThat(bar2).isEqualTo(bar1); } @Test - public void testTypeVariablesViaTypeParameter() throws Exception { + public void testTypeVariablesViaTypeParameter() { Gson gson = new Gson(); Foo original = new Foo<>("e", 5, false); original.map.put("f", Arrays.asList(6, 7)); Type type = new TypeToken>() {}.getType(); String json = gson.toJson(original, type); - assertEquals("{\"someSField\":\"e\",\"someTField\":5,\"map\":{\"f\":[6,7]},\"redField\":false}", - json); - assertEquals(original, gson.>fromJson(json, type)); + assertThat(json) + .isEqualTo("{\"someSField\":\"e\",\"someTField\":5,\"map\":{\"f\":[6,7]},\"redField\":false}"); + assertThat(gson.>fromJson(json, type)).isEqualTo(original); } @Test - public void testBasicTypeVariables() throws Exception { + public void testBasicTypeVariables() { Gson gson = new Gson(); Blue blue1 = new Blue(true); String json = gson.toJson(blue1); Blue blue2 = gson.fromJson(json, Blue.class); - assertEquals(blue1, blue2); + assertThat(blue2).isEqualTo(blue1); } @SuppressWarnings("overrides") // for missing hashCode() override diff --git a/gson/src/test/java/com/google/gson/functional/UncategorizedTest.java b/gson/src/test/java/com/google/gson/functional/UncategorizedTest.java index 58171de0b7..7b9b6c566f 100644 --- a/gson/src/test/java/com/google/gson/functional/UncategorizedTest.java +++ b/gson/src/test/java/com/google/gson/functional/UncategorizedTest.java @@ -15,9 +15,7 @@ */ package com.google.gson.functional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.fail; import com.google.gson.Gson; @@ -69,13 +67,13 @@ public void testObjectEqualButNotSameSerialization() throws Exception { ClassOverridingEquals objB = new ClassOverridingEquals(); objB.ref = objA; String json = gson.toJson(objB); - assertEquals(objB.getExpectedJson(), json); + assertThat(json).isEqualTo(objB.getExpectedJson()); } @Test public void testStaticFieldsAreNotSerialized() { BagOfPrimitives target = new BagOfPrimitives(); - assertFalse(gson.toJson(target).contains("DEFAULT_VALUE")); + assertThat(gson.toJson(target).contains("DEFAULT_VALUE")).isFalse(); } @Test @@ -83,7 +81,7 @@ public void testGsonInstanceReusableForSerializationAndDeserialization() { BagOfPrimitives bag = new BagOfPrimitives(); String json = gson.toJson(bag); BagOfPrimitives deserialized = gson.fromJson(json, BagOfPrimitives.class); - assertEquals(bag, deserialized); + assertThat(deserialized).isEqualTo(bag); } /** @@ -96,13 +94,13 @@ public void testReturningDerivedClassesDuringDeserialization() { Gson gson = new GsonBuilder().registerTypeAdapter(Base.class, new BaseTypeAdapter()).create(); String json = "{\"opType\":\"OP1\"}"; Base base = gson.fromJson(json, Base.class); - assertTrue(base instanceof Derived1); - assertEquals(OperationType.OP1, base.opType); + assertThat(base).isInstanceOf(Derived1.class); + assertThat(base.opType).isEqualTo(OperationType.OP1); json = "{\"opType\":\"OP2\"}"; base = gson.fromJson(json, Base.class); - assertTrue(base instanceof Derived2); - assertEquals(OperationType.OP2, base.opType); + assertThat(base).isInstanceOf(Derived2.class); + assertThat(base.opType).isEqualTo(OperationType.OP2); } /** @@ -113,7 +111,7 @@ public void testReturningDerivedClassesDuringDeserialization() { public void testTrailingWhitespace() throws Exception { List integers = gson.fromJson("[1,2,3] \n\n ", new TypeToken>() {}.getType()); - assertEquals(Arrays.asList(1, 2, 3), integers); + assertThat(integers).containsExactly(1, 2, 3).inOrder(); } private enum OperationType { OP1, OP2 } diff --git a/gson/src/test/java/com/google/gson/functional/VersioningTest.java b/gson/src/test/java/com/google/gson/functional/VersioningTest.java index 49dabcab2d..c9f6621d87 100644 --- a/gson/src/test/java/com/google/gson/functional/VersioningTest.java +++ b/gson/src/test/java/com/google/gson/functional/VersioningTest.java @@ -15,10 +15,7 @@ */ package com.google.gson.functional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static com.google.common.truth.Truth.assertThat; import com.google.gson.Gson; import com.google.gson.GsonBuilder; @@ -48,15 +45,15 @@ public void testVersionedUntilSerialization() { Version1 target = new Version1(); Gson gson = gsonWithVersion(1.29); String json = gson.toJson(target); - assertTrue(json.contains("\"a\":" + A)); + assertThat(json).contains("\"a\":" + A); gson = gsonWithVersion(1.3); json = gson.toJson(target); - assertFalse(json.contains("\"a\":" + A)); + assertThat(json).doesNotContain("\"a\":" + A); gson = gsonWithVersion(1.31); json = gson.toJson(target); - assertFalse(json.contains("\"a\":" + A)); + assertThat(json).doesNotContain("\"a\":" + A); } @Test @@ -65,15 +62,15 @@ public void testVersionedUntilDeserialization() { Gson gson = gsonWithVersion(1.29); Version1 version1 = gson.fromJson(json, Version1.class); - assertEquals(3, version1.a); + assertThat(version1.a).isEqualTo(3); gson = gsonWithVersion(1.3); version1 = gson.fromJson(json, Version1.class); - assertEquals(A, version1.a); + assertThat(version1.a).isEqualTo(A); gson = gsonWithVersion(1.31); version1 = gson.fromJson(json, Version1.class); - assertEquals(A, version1.a); + assertThat(version1.a).isEqualTo(A); } @Test @@ -81,7 +78,7 @@ public void testVersionedClassesSerialization() { Gson gson = gsonWithVersion(1.0); String json1 = gson.toJson(new Version1()); String json2 = gson.toJson(new Version1_1()); - assertEquals(json1, json2); + assertThat(json2).isEqualTo(json1); } @Test @@ -89,18 +86,18 @@ public void testVersionedClassesDeserialization() { Gson gson = gsonWithVersion(1.0); String json = "{\"a\":3,\"b\":4,\"c\":5}"; Version1 version1 = gson.fromJson(json, Version1.class); - assertEquals(3, version1.a); - assertEquals(4, version1.b); + assertThat(version1.a).isEqualTo(3); + assertThat(version1.b).isEqualTo(4); Version1_1 version1_1 = gson.fromJson(json, Version1_1.class); - assertEquals(3, version1_1.a); - assertEquals(4, version1_1.b); - assertEquals(C, version1_1.c); + assertThat(version1_1.a).isEqualTo(3); + assertThat(version1_1.b).isEqualTo(4); + assertThat(version1_1.c).isEqualTo(C); } @Test public void testIgnoreLaterVersionClassSerialization() { Gson gson = gsonWithVersion(1.0); - assertEquals("null", gson.toJson(new Version1_2())); + assertThat(gson.toJson(new Version1_2())).isEqualTo("null"); } @Test @@ -110,14 +107,14 @@ public void testIgnoreLaterVersionClassDeserialization() { Version1_2 version1_2 = gson.fromJson(json, Version1_2.class); // Since the class is versioned to be after 1.0, we expect null // This is the new behavior in Gson 2.0 - assertNull(version1_2); + assertThat(version1_2).isNull(); } @Test public void testVersionedGsonWithUnversionedClassesSerialization() { Gson gson = gsonWithVersion(1.0); BagOfPrimitives target = new BagOfPrimitives(10, 20, false, "stringValue"); - assertEquals(target.getExpectedJson(), gson.toJson(target)); + assertThat(gson.toJson(target)).isEqualTo(target.getExpectedJson()); } @Test @@ -130,7 +127,7 @@ public void testVersionedGsonWithUnversionedClassesDeserialization() { expected.intValue = 20; expected.booleanValue = false; BagOfPrimitives actual = gson.fromJson(json, BagOfPrimitives.class); - assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); } @Test @@ -138,19 +135,19 @@ public void testVersionedGsonMixingSinceAndUntilSerialization() { Gson gson = gsonWithVersion(1.0); SinceUntilMixing target = new SinceUntilMixing(); String json = gson.toJson(target); - assertFalse(json.contains("\"b\":" + B)); + assertThat(json).doesNotContain("\"b\":" + B); gson = gsonWithVersion(1.2); json = gson.toJson(target); - assertTrue(json.contains("\"b\":" + B)); + assertThat(json).contains("\"b\":" + B); gson = gsonWithVersion(1.3); json = gson.toJson(target); - assertFalse(json.contains("\"b\":" + B)); + assertThat(json).doesNotContain("\"b\":" + B); gson = gsonWithVersion(1.4); json = gson.toJson(target); - assertFalse(json.contains("\"b\":" + B)); + assertThat(json).doesNotContain("\"b\":" + B); } @Test @@ -158,23 +155,23 @@ public void testVersionedGsonMixingSinceAndUntilDeserialization() { String json = "{\"a\":5,\"b\":6}"; Gson gson = gsonWithVersion(1.0); SinceUntilMixing result = gson.fromJson(json, SinceUntilMixing.class); - assertEquals(5, result.a); - assertEquals(B, result.b); + assertThat(result.a).isEqualTo(5); + assertThat(result.b).isEqualTo(B); gson = gsonWithVersion(1.2); result = gson.fromJson(json, SinceUntilMixing.class); - assertEquals(5, result.a); - assertEquals(6, result.b); + assertThat(result.a).isEqualTo(5); + assertThat(result.b).isEqualTo(6); gson = gsonWithVersion(1.3); result = gson.fromJson(json, SinceUntilMixing.class); - assertEquals(5, result.a); - assertEquals(B, result.b); + assertThat(result.a).isEqualTo(5); + assertThat(result.b).isEqualTo(B); gson = gsonWithVersion(1.4); result = gson.fromJson(json, SinceUntilMixing.class); - assertEquals(5, result.a); - assertEquals(B, result.b); + assertThat(result.a).isEqualTo(5); + assertThat(result.b).isEqualTo(B); } private static class Version1 { diff --git a/gson/src/test/java/com/google/gson/internal/bind/JsonTreeReaderTest.java b/gson/src/test/java/com/google/gson/internal/bind/JsonTreeReaderTest.java index 14ecbc9098..5faa718015 100644 --- a/gson/src/test/java/com/google/gson/internal/bind/JsonTreeReaderTest.java +++ b/gson/src/test/java/com/google/gson/internal/bind/JsonTreeReaderTest.java @@ -133,7 +133,7 @@ public JsonElement deepCopy() { reader.peek(); fail(); } catch (MalformedJsonException expected) { - assertThat( expected.getMessage()).isEqualTo("Custom JsonElement subclass " + CustomSubclass.class.getName() + " is not supported"); + assertThat(expected.getMessage()).isEqualTo("Custom JsonElement subclass " + CustomSubclass.class.getName() + " is not supported"); } } From b075fafa217d65ffef29099d561c08ffea5ed73e Mon Sep 17 00:00:00 2001 From: maicolAntali Date: Sat, 28 Jan 2023 15:13:41 +0100 Subject: [PATCH 11/14] Replaces `List.of` with `Arrays.asList` to grant legacy --- .../com/google/gson/functional/StreamingTypeAdaptersTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gson/src/test/java/com/google/gson/functional/StreamingTypeAdaptersTest.java b/gson/src/test/java/com/google/gson/functional/StreamingTypeAdaptersTest.java index f2e8653e5c..6e13624f22 100644 --- a/gson/src/test/java/com/google/gson/functional/StreamingTypeAdaptersTest.java +++ b/gson/src/test/java/com/google/gson/functional/StreamingTypeAdaptersTest.java @@ -229,7 +229,7 @@ public void testFromJsonTree() { Truck truck = truckAdapter.fromJsonTree(truckObject); assertThat(truck.horsePower).isEqualTo(300.0); - assertThat(truck.passengers).isEqualTo(List.of(new Person("Jesse", 30))); + assertThat(truck.passengers).isEqualTo(Arrays.asList(new Person("Jesse", 30))); } static class Truck { From 9229737203752dc066ac473761ad5c2856ec830c Mon Sep 17 00:00:00 2001 From: maicolAntali Date: Mon, 30 Jan 2023 08:47:30 +0100 Subject: [PATCH 12/14] Simplify `==` asserts --- .../src/test/java/com/google/gson/functional/ArrayTest.java | 6 +++--- .../java/com/google/gson/functional/CollectionTest.java | 2 +- .../java/com/google/gson/functional/ExposeFieldsTest.java | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/gson/src/test/java/com/google/gson/functional/ArrayTest.java b/gson/src/test/java/com/google/gson/functional/ArrayTest.java index b614f67ab4..884442d308 100644 --- a/gson/src/test/java/com/google/gson/functional/ArrayTest.java +++ b/gson/src/test/java/com/google/gson/functional/ArrayTest.java @@ -77,13 +77,13 @@ public void testEmptyArraySerialization() { @Test public void testEmptyArrayDeserialization() { int[] actualObject = gson.fromJson("[]", int[].class); - assertThat(actualObject.length == 0).isTrue(); + assertThat(actualObject).hasLength(0); Integer[] actualObject2 = gson.fromJson("[]", Integer[].class); - assertThat(actualObject2.length == 0).isTrue(); + assertThat(actualObject2).hasLength(0); actualObject = gson.fromJson("[ ]", int[].class); - assertThat(actualObject.length == 0).isTrue(); + assertThat(actualObject).hasLength(0); } @Test diff --git a/gson/src/test/java/com/google/gson/functional/CollectionTest.java b/gson/src/test/java/com/google/gson/functional/CollectionTest.java index 3d444c7fbb..897339b968 100644 --- a/gson/src/test/java/com/google/gson/functional/CollectionTest.java +++ b/gson/src/test/java/com/google/gson/functional/CollectionTest.java @@ -414,7 +414,7 @@ public void testSetDeserialization() { Set set = gson.fromJson(json, type); assertThat(set.size()).isEqualTo(2); for (Entry entry : set) { - assertThat(entry.value == 1 || entry.value == 2).isTrue(); + assertThat(entry.value).isAnyOf(1, 2); } } diff --git a/gson/src/test/java/com/google/gson/functional/ExposeFieldsTest.java b/gson/src/test/java/com/google/gson/functional/ExposeFieldsTest.java index 97b0bd39fc..3215efdfff 100644 --- a/gson/src/test/java/com/google/gson/functional/ExposeFieldsTest.java +++ b/gson/src/test/java/com/google/gson/functional/ExposeFieldsTest.java @@ -79,9 +79,9 @@ public void testExposeAnnotationDeserialization() { String json = "{a:3,b:4,d:20.0}"; ClassWithExposedFields target = gson.fromJson(json, ClassWithExposedFields.class); - assertThat((int) target.a).isEqualTo(3); + assertThat(target.a).isEqualTo(3); assertThat(target.b).isNull(); - assertThat(target.d == 20).isFalse(); + assertThat(target.d).isNotEqualTo(20); } @Test From 8bfd0bd1885e39e0ea6cce6bc2e88ad5c726d2d7 Mon Sep 17 00:00:00 2001 From: maicolAntali Date: Mon, 30 Jan 2023 09:39:51 +0100 Subject: [PATCH 13/14] Simplify `.contain()` asserts + Minor fixes --- .../com/google/gson/JsonArrayAsListTest.java | 6 ++-- .../java/com/google/gson/JsonArrayTest.java | 4 +-- .../java/com/google/gson/JsonObjectTest.java | 3 +- .../com/google/gson/functional/ArrayTest.java | 14 ++++---- .../functional/CircularReferenceTest.java | 2 +- .../gson/functional/CollectionTest.java | 34 +++++++++---------- .../functional/CustomTypeAdaptersTest.java | 14 ++++---- .../functional/DefaultTypeAdaptersTest.java | 26 +++++++------- .../com/google/gson/functional/EnumTest.java | 5 ++- .../google/gson/functional/EscapingTest.java | 6 ++-- .../ExclusionStrategyFunctionalTest.java | 18 +++++----- .../gson/functional/InheritanceTest.java | 8 ++--- .../gson/functional/UncategorizedTest.java | 4 +-- .../google/gson/metrics/PerformanceTest.java | 4 +-- 14 files changed, 72 insertions(+), 76 deletions(-) diff --git a/gson/src/test/java/com/google/gson/JsonArrayAsListTest.java b/gson/src/test/java/com/google/gson/JsonArrayAsListTest.java index 8c0612042e..0fb17b5698 100644 --- a/gson/src/test/java/com/google/gson/JsonArrayAsListTest.java +++ b/gson/src/test/java/com/google/gson/JsonArrayAsListTest.java @@ -202,9 +202,9 @@ public void testContains() { a.add(1); List list = a.asList(); - assertThat(list.contains(new JsonPrimitive(1))).isTrue(); - assertThat(list.contains(new JsonPrimitive(2))).isFalse(); - assertThat(list.contains(null)).isFalse(); + assertThat(list).contains(new JsonPrimitive(1)); + assertThat(list).doesNotContain(new JsonPrimitive(2)); + assertThat(list).doesNotContain(null); @SuppressWarnings({"unlikely-arg-type", "CollectionIncompatibleType"}) boolean containsInt = list.contains(1); // should only contain JsonPrimitive(1) diff --git a/gson/src/test/java/com/google/gson/JsonArrayTest.java b/gson/src/test/java/com/google/gson/JsonArrayTest.java index c1103bec7c..21deb729b1 100644 --- a/gson/src/test/java/com/google/gson/JsonArrayTest.java +++ b/gson/src/test/java/com/google/gson/JsonArrayTest.java @@ -67,12 +67,12 @@ public void testRemove() { JsonPrimitive a = new JsonPrimitive("a"); array.add(a); assertThat(array.remove(a)).isTrue(); - assertThat(array.contains(a)).isFalse(); + assertThat(array).doesNotContain(a); array.add(a); array.add(new JsonPrimitive("b")); assertThat(array.remove(1).getAsString()).isEqualTo("b"); assertThat(array).hasSize(1); - assertThat(array.contains(a)).isTrue(); + assertThat(array).contains(a); } @Test diff --git a/gson/src/test/java/com/google/gson/JsonObjectTest.java b/gson/src/test/java/com/google/gson/JsonObjectTest.java index d26afc4b24..d0da6abb78 100644 --- a/gson/src/test/java/com/google/gson/JsonObjectTest.java +++ b/gson/src/test/java/com/google/gson/JsonObjectTest.java @@ -255,8 +255,7 @@ public void testKeySet() { assertThat(a.size()).isEqualTo(2); assertThat(a.keySet()).hasSize(2); - assertThat(a.keySet().contains("foo")).isTrue(); - assertThat(a.keySet().contains("bar")).isTrue(); + assertThat(a.keySet()).containsExactly("foo", "bar").inOrder(); a.addProperty("1", true); a.addProperty("2", false); diff --git a/gson/src/test/java/com/google/gson/functional/ArrayTest.java b/gson/src/test/java/com/google/gson/functional/ArrayTest.java index 884442d308..85abb1ec4e 100644 --- a/gson/src/test/java/com/google/gson/functional/ArrayTest.java +++ b/gson/src/test/java/com/google/gson/functional/ArrayTest.java @@ -197,9 +197,9 @@ public void testArrayOfCollectionDeserialization() { public void testArrayOfPrimitivesAsObjectsSerialization() { Object[] objs = new Object[] {1, "abc", 0.3f, 5L}; String json = gson.toJson(objs); - assertThat(json.contains("abc")).isTrue(); - assertThat(json.contains("0.3")).isTrue(); - assertThat(json.contains("5")).isTrue(); + assertThat(json).contains("abc"); + assertThat(json).contains("0.3"); + assertThat(json).contains("5"); } @Test @@ -223,8 +223,8 @@ public void testObjectArrayWithNonPrimitivesSerialization() { Object[] objects = {classWithObjects, bagOfPrimitives}; String json = gson.toJson(objects); - assertThat(json.contains(classWithObjectsJson)).isTrue(); - assertThat(json.contains(bagOfPrimitivesJson)).isTrue(); + assertThat(json).contains(classWithObjectsJson); + assertThat(json).contains(bagOfPrimitivesJson); } @Test @@ -250,8 +250,8 @@ public void testMultidimensionalArraysSerialization() { {"Alcoa Inc", "29.01", "0.42", "1.47", "4/1 12:00am", "Manufacturing"} }; String json = gson.toJson(items); - assertThat(json.contains("[[\"3m Co")).isTrue(); - assertThat(json.contains("Manufacturing\"]]")).isTrue(); + assertThat(json).contains("[[\"3m Co"); + assertThat(json).contains("Manufacturing\"]]"); } @Test diff --git a/gson/src/test/java/com/google/gson/functional/CircularReferenceTest.java b/gson/src/test/java/com/google/gson/functional/CircularReferenceTest.java index 582ec4d724..b98435f1d0 100644 --- a/gson/src/test/java/com/google/gson/functional/CircularReferenceTest.java +++ b/gson/src/test/java/com/google/gson/functional/CircularReferenceTest.java @@ -64,7 +64,7 @@ public void testSelfReferenceIgnoredInSerialization() { objA.ref = objA; String json = gson.toJson(objA); - assertThat(json.contains("ref")).isFalse(); // self-reference is ignored + assertThat(json).doesNotContain("ref"); // self-reference is ignored } @Test diff --git a/gson/src/test/java/com/google/gson/functional/CollectionTest.java b/gson/src/test/java/com/google/gson/functional/CollectionTest.java index 897339b968..3507c94dba 100644 --- a/gson/src/test/java/com/google/gson/functional/CollectionTest.java +++ b/gson/src/test/java/com/google/gson/functional/CollectionTest.java @@ -99,8 +99,8 @@ public void testLinkedListSerialization() { list.add("a2"); Type linkedListType = new TypeToken>() {}.getType(); String json = gson.toJson(list, linkedListType); - assertThat(json.contains("a1")).isTrue(); - assertThat(json.contains("a2")).isTrue(); + assertThat(json).contains("a1"); + assertThat(json).contains("a2"); } @Test @@ -119,8 +119,8 @@ public void testQueueSerialization() { queue.add("a2"); Type queueType = new TypeToken>() {}.getType(); String json = gson.toJson(queue, queueType); - assertThat(json.contains("a1")).isTrue(); - assertThat(json.contains("a2")).isTrue(); + assertThat(json).contains("a1"); + assertThat(json).contains("a2"); } @Test @@ -238,7 +238,7 @@ public void testCollectionOfBagOfPrimitivesSerialization() { assertThat(result.startsWith("[")).isTrue(); assertThat(result.endsWith("]")).isTrue(); for (BagOfPrimitives obj : target) { - assertThat(result.contains(obj.getExpectedJson())).isTrue(); + assertThat(result).contains(obj.getExpectedJson()); } } @@ -248,8 +248,7 @@ public void testCollectionOfStringsDeserialization() { Type collectionType = new TypeToken>() { }.getType(); Collection target = gson.fromJson(json, collectionType); - assertThat(target.contains("Hello")).isTrue(); - assertThat(target.contains("World")).isTrue(); + assertThat(target).containsExactly("Hello", "World").inOrder(); } @Test @@ -263,7 +262,7 @@ public void testObjectCollectionSerialization() { BagOfPrimitives bag1 = new BagOfPrimitives(); Collection target = Arrays.asList(bag1, bag1, "test"); String json = gson.toJson(target); - assertThat(json.contains(bag1.getExpectedJson())).isTrue(); + assertThat(json).contains(bag1.getExpectedJson()); } @Test @@ -275,8 +274,7 @@ public void testRawCollectionDeserializationNotAlllowed() { json = "[\"Hello\", \"World\"]"; Collection strings = gson.fromJson(json, Collection.class); - assertThat(strings.contains("Hello")).isTrue(); - assertThat(strings.contains("World")).isTrue(); + assertThat(strings).containsExactly("Hello", "World").inOrder(); } @Test @@ -312,8 +310,8 @@ public void testWildcardPrimitiveCollectionDeserilaization() { Type collectionType = new TypeToken>() { }.getType(); Collection target = gson.fromJson(json, collectionType); assertThat(target.size()).isEqualTo(9); - assertThat(target.contains(1)).isTrue(); - assertThat(target.contains(9)).isTrue(); + assertThat(target).contains(1); + assertThat(target).contains(2); } @Test @@ -326,14 +324,14 @@ public void testWildcardCollectionField() { ObjectWithWildcardCollection target = new ObjectWithWildcardCollection(collection); String json = gson.toJson(target); - assertThat(json.contains(objA.getExpectedJson())).isTrue(); - assertThat(json.contains(objB.getExpectedJson())).isTrue(); + assertThat(json).contains(objA.getExpectedJson()); + assertThat(json).contains(objB.getExpectedJson()); target = gson.fromJson(json, ObjectWithWildcardCollection.class); Collection deserializedCollection = target.getCollection(); assertThat(deserializedCollection.size()).isEqualTo(2); - assertThat(deserializedCollection.contains(objA)).isTrue(); - assertThat(deserializedCollection.contains(objB)).isTrue(); + assertThat(deserializedCollection).contains(objA); + assertThat(deserializedCollection).contains(objB); } @Test @@ -404,8 +402,8 @@ public void testSetSerialization() { set.add(new Entry(1)); set.add(new Entry(2)); String json = gson.toJson(set); - assertThat(json.contains("1")).isTrue(); - assertThat(json.contains("2")).isTrue(); + assertThat(json).contains("1"); + assertThat(json).contains("2"); } @Test public void testSetDeserialization() { diff --git a/gson/src/test/java/com/google/gson/functional/CustomTypeAdaptersTest.java b/gson/src/test/java/com/google/gson/functional/CustomTypeAdaptersTest.java index cfcf166bd1..3c59cb8115 100644 --- a/gson/src/test/java/com/google/gson/functional/CustomTypeAdaptersTest.java +++ b/gson/src/test/java/com/google/gson/functional/CustomTypeAdaptersTest.java @@ -171,11 +171,11 @@ public JsonElement serialize(Base src, Type typeOfSrc, JsonSerializationContext }).create(); Base b = new Base(); String json = gson.toJson(b); - assertThat(json.contains("value")).isTrue(); + assertThat(json).contains("value"); b = new Derived(); json = gson.toJson(b, Base.class); - assertThat(json.contains("value")).isTrue(); - assertThat(json.contains("derivedValue")).isFalse(); + assertThat(json).contains("value"); + assertThat(json).doesNotContain("derivedValue"); } private static class Base { @@ -332,7 +332,7 @@ public void testCustomAdapterInvokedForCollectionElementSerializationWithType() Set setOfHolders = new HashSet<>(); setOfHolders.add(holder); String json = gson.toJson(setOfHolders, setType); - assertThat(json.contains("Jacob:Tomaw")).isTrue(); + assertThat(json).contains("Jacob:Tomaw"); } // Test created from Issue 70 @@ -345,7 +345,7 @@ public void testCustomAdapterInvokedForCollectionElementSerialization() { Set setOfHolders = new HashSet<>(); setOfHolders.add(holder); String json = gson.toJson(setOfHolders); - assertThat(json.contains("Jacob:Tomaw")).isTrue(); + assertThat(json).contains("Jacob:Tomaw"); } // Test created from Issue 70 @@ -373,7 +373,7 @@ public void testCustomAdapterInvokedForMapElementSerializationWithType() { Map mapOfHolders = new HashMap<>(); mapOfHolders.put("foo", holder); String json = gson.toJson(mapOfHolders, mapType); - assertThat(json.contains("\"foo\":\"Jacob:Tomaw\"")).isTrue(); + assertThat(json).contains("\"foo\":\"Jacob:Tomaw\""); } // Test created from Issue 70 @@ -386,7 +386,7 @@ public void testCustomAdapterInvokedForMapElementSerialization() { Map mapOfHolders = new HashMap<>(); mapOfHolders.put("foo", holder); String json = gson.toJson(mapOfHolders); - assertThat(json.contains("\"foo\":\"Jacob:Tomaw\"")).isTrue(); + assertThat(json).contains("\"foo\":\"Jacob:Tomaw\""); } // Test created from Issue 70 diff --git a/gson/src/test/java/com/google/gson/functional/DefaultTypeAdaptersTest.java b/gson/src/test/java/com/google/gson/functional/DefaultTypeAdaptersTest.java index 752a7d0630..33ebc682b4 100644 --- a/gson/src/test/java/com/google/gson/functional/DefaultTypeAdaptersTest.java +++ b/gson/src/test/java/com/google/gson/functional/DefaultTypeAdaptersTest.java @@ -435,12 +435,12 @@ public void testDefaultDateDeserializationUsingBuilder() { public void testDefaultCalendarSerialization() { Gson gson = new GsonBuilder().create(); String json = gson.toJson(Calendar.getInstance()); - assertThat(json.contains("year")).isTrue(); - assertThat(json.contains("month")).isTrue(); - assertThat(json.contains("dayOfMonth")).isTrue(); - assertThat(json.contains("hourOfDay")).isTrue(); - assertThat(json.contains("minute")).isTrue(); - assertThat(json.contains("second")).isTrue(); + assertThat(json).contains("year"); + assertThat(json).contains("month"); + assertThat(json).contains("dayOfMonth"); + assertThat(json).contains("hourOfDay"); + assertThat(json).contains("minute"); + assertThat(json).contains("second"); } @Test @@ -461,12 +461,12 @@ public void testDefaultGregorianCalendarSerialization() { Gson gson = new GsonBuilder().create(); GregorianCalendar cal = new GregorianCalendar(); String json = gson.toJson(cal); - assertThat(json.contains("year")).isTrue(); - assertThat(json.contains("month")).isTrue(); - assertThat(json.contains("dayOfMonth")).isTrue(); - assertThat(json.contains("hourOfDay")).isTrue(); - assertThat(json.contains("minute")).isTrue(); - assertThat(json.contains("second")).isTrue(); + assertThat(json).contains("year"); + assertThat(json).contains("month"); + assertThat(json).contains("dayOfMonth"); + assertThat(json).contains("hourOfDay"); + assertThat(json).contains("minute"); + assertThat(json).contains("second"); } @Test @@ -683,7 +683,7 @@ public void testTreeSetDeserialization() { String json = "['Value1']"; Type type = new TypeToken>() {}.getType(); TreeSet treeSet = gson.fromJson(json, type); - assertThat(treeSet.contains("Value1")).isTrue(); + assertThat(treeSet).contains("Value1"); } @Test diff --git a/gson/src/test/java/com/google/gson/functional/EnumTest.java b/gson/src/test/java/com/google/gson/functional/EnumTest.java index afe3b029da..0a9d0cde6c 100644 --- a/gson/src/test/java/com/google/gson/functional/EnumTest.java +++ b/gson/src/test/java/com/google/gson/functional/EnumTest.java @@ -173,9 +173,8 @@ public void testEnumSet() { Type type = new TypeToken>() {}.getType(); EnumSet bar = gson.fromJson(json, type); - assertThat(bar.contains(Roshambo.ROCK)).isTrue(); - assertThat(bar.contains(Roshambo.PAPER)).isTrue(); - assertThat(bar.contains(Roshambo.SCISSORS)).isFalse(); + assertThat(bar).containsExactly(Roshambo.ROCK, Roshambo.PAPER).inOrder(); + assertThat(bar).doesNotContain(Roshambo.SCISSORS);; } @Test diff --git a/gson/src/test/java/com/google/gson/functional/EscapingTest.java b/gson/src/test/java/com/google/gson/functional/EscapingTest.java index e917a05af8..deaca904bf 100644 --- a/gson/src/test/java/com/google/gson/functional/EscapingTest.java +++ b/gson/src/test/java/com/google/gson/functional/EscapingTest.java @@ -65,9 +65,9 @@ public void testEscapeAllHtmlCharacters() { public void testEscapingObjectFields() { BagOfPrimitives objWithPrimitives = new BagOfPrimitives(1L, 1, true, "test with\"