Port all Junit assert to Truth asserts (#2304)

* Port Junit assert to Truth in `com.google.gson.stream`

* Port Junit assert to Truth in `com.google.gson.regression`

* Port Junit assert to Truth in `om.google.gson.reflect`

* Port Junit assert to Truth in `com.google.gson.metrics`

* Port Junit assert to Truth in `com.google.gson.internal`

* Port Junit assert to Truth in `com.google.gson.internal.sql`

* Port Junit assert to Truth in `com.google.gson.internal.reflect`

* Port Junit assert to Truth in `com.google.gson.internal.bind`

* Port Junit assert to Truth in `com.google.gson.internal.bind.util`

* Port Junit assert to Truth in `com.google.gson.functional`

* Replaces `List.of` with `Arrays.asList` to grant legacy

* Simplify `==` asserts

* Simplify `.contain()` asserts + Minor fixes

* Simplify asserts
This commit is contained in:
Maicol 2023-01-31 20:20:54 +01:00 committed by GitHub
parent 41de7ce75b
commit 49b00d1a86
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
87 changed files with 2322 additions and 2489 deletions

View File

@ -202,9 +202,9 @@ public class JsonArrayAsListTest {
a.add(1); a.add(1);
List<JsonElement> list = a.asList(); List<JsonElement> list = a.asList();
assertThat(list.contains(new JsonPrimitive(1))).isTrue(); assertThat(list).contains(new JsonPrimitive(1));
assertThat(list.contains(new JsonPrimitive(2))).isFalse(); assertThat(list).doesNotContain(new JsonPrimitive(2));
assertThat(list.contains(null)).isFalse(); assertThat(list).doesNotContain(null);
@SuppressWarnings({"unlikely-arg-type", "CollectionIncompatibleType"}) @SuppressWarnings({"unlikely-arg-type", "CollectionIncompatibleType"})
boolean containsInt = list.contains(1); // should only contain JsonPrimitive(1) boolean containsInt = list.contains(1); // should only contain JsonPrimitive(1)

View File

@ -67,12 +67,12 @@ public final class JsonArrayTest {
JsonPrimitive a = new JsonPrimitive("a"); JsonPrimitive a = new JsonPrimitive("a");
array.add(a); array.add(a);
assertThat(array.remove(a)).isTrue(); assertThat(array.remove(a)).isTrue();
assertThat(array.contains(a)).isFalse(); assertThat(array).doesNotContain(a);
array.add(a); array.add(a);
array.add(new JsonPrimitive("b")); array.add(new JsonPrimitive("b"));
assertThat(array.remove(1).getAsString()).isEqualTo("b"); assertThat(array.remove(1).getAsString()).isEqualTo("b");
assertThat(array).hasSize(1); assertThat(array).hasSize(1);
assertThat(array.contains(a)).isTrue(); assertThat(array).contains(a);
} }
@Test @Test

View File

@ -255,8 +255,7 @@ public class JsonObjectTest {
assertThat(a.size()).isEqualTo(2); assertThat(a.size()).isEqualTo(2);
assertThat(a.keySet()).hasSize(2); assertThat(a.keySet()).hasSize(2);
assertThat(a.keySet().contains("foo")).isTrue(); assertThat(a.keySet()).containsExactly("foo", "bar").inOrder();
assertThat(a.keySet().contains("bar")).isTrue();
a.addProperty("1", true); a.addProperty("1", true);
a.addProperty("2", false); a.addProperty("2", false);

View File

@ -16,10 +16,7 @@
package com.google.gson.functional; package com.google.gson.functional;
import static org.junit.Assert.assertArrayEquals; import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import com.google.gson.Gson; import com.google.gson.Gson;
@ -31,6 +28,7 @@ import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type; import java.lang.reflect.Type;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection; import java.util.Collection;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
@ -51,14 +49,14 @@ public class ArrayTest {
@Test @Test
public void testTopLevelArrayOfIntsSerialization() { public void testTopLevelArrayOfIntsSerialization() {
int[] target = {1, 2, 3, 4, 5, 6, 7, 8, 9}; 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 @Test
public void testTopLevelArrayOfIntsDeserialization() { public void testTopLevelArrayOfIntsDeserialization() {
int[] expected = {1, 2, 3, 4, 5, 6, 7, 8, 9}; 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); int[] actual = gson.fromJson("[1,2,3,4,5,6,7,8,9]", int[].class);
assertArrayEquals(expected, actual); assertThat(actual).isEqualTo(expected);
} }
@Test @Test
@ -74,19 +72,19 @@ public class ArrayTest {
@Test @Test
public void testEmptyArraySerialization() { public void testEmptyArraySerialization() {
int[] target = {}; int[] target = {};
assertEquals("[]", gson.toJson(target)); assertThat(gson.toJson(target)).isEqualTo("[]");
} }
@Test @Test
public void testEmptyArrayDeserialization() { public void testEmptyArrayDeserialization() {
int[] actualObject = gson.fromJson("[]", int[].class); int[] actualObject = gson.fromJson("[]", int[].class);
assertTrue(actualObject.length == 0); assertThat(actualObject).hasLength(0);
Integer[] actualObject2 = gson.fromJson("[]", Integer[].class); Integer[] actualObject2 = gson.fromJson("[]", Integer[].class);
assertTrue(actualObject2.length == 0); assertThat(actualObject2).hasLength(0);
actualObject = gson.fromJson("[ ]", int[].class); actualObject = gson.fromJson("[ ]", int[].class);
assertTrue(actualObject.length == 0); assertThat(actualObject).hasLength(0);
} }
@Test @Test
@ -94,7 +92,7 @@ public class ArrayTest {
String[] array = {"foo", null, "bar"}; String[] array = {"foo", null, "bar"};
String expected = "[\"foo\",null,\"bar\"]"; String expected = "[\"foo\",null,\"bar\"]";
String json = gson.toJson(array); String json = gson.toJson(array);
assertEquals(expected, json); assertThat(json).isEqualTo(expected);
} }
@Test @Test
@ -102,9 +100,7 @@ public class ArrayTest {
String json = "[\"foo\",null,\"bar\"]"; String json = "[\"foo\",null,\"bar\"]";
String[] expected = {"foo", null, "bar"}; String[] expected = {"foo", null, "bar"};
String[] target = gson.fromJson(json, expected.getClass()); String[] target = gson.fromJson(json, expected.getClass());
for (int i = 0; i < expected.length; ++i) { assertThat(target).asList().containsAnyIn(expected);
assertEquals(expected[i], target[i]);
}
} }
@Test @Test
@ -112,13 +108,13 @@ public class ArrayTest {
BagOfPrimitives[] array = new BagOfPrimitives[1]; BagOfPrimitives[] array = new BagOfPrimitives[1];
array[0] = null; array[0] = null;
String json = gson.toJson(array); String json = gson.toJson(array);
assertEquals("[null]", json); assertThat(json).isEqualTo("[null]");
} }
@Test @Test
public void testSingleNullInArrayDeserialization() { public void testSingleNullInArrayDeserialization() {
BagOfPrimitives[] array = gson.fromJson("[null]", BagOfPrimitives[].class); BagOfPrimitives[] array = gson.fromJson("[null]", BagOfPrimitives[].class);
assertNull(array[0]); assertThat(array).asList().containsExactly((Object) null);
} }
@Test @Test
@ -127,40 +123,38 @@ public class ArrayTest {
String[] array = {"foo", null, "bar"}; String[] array = {"foo", null, "bar"};
String expected = "[\"foo\",null,\"bar\"]"; String expected = "[\"foo\",null,\"bar\"]";
String json = gson.toJson(array); String json = gson.toJson(array);
assertEquals(expected, json); assertThat(json).isEqualTo(expected);
} }
@Test @Test
public void testArrayOfStringsSerialization() { public void testArrayOfStringsSerialization() {
String[] target = {"Hello", "World"}; String[] target = {"Hello", "World"};
assertEquals("[\"Hello\",\"World\"]", gson.toJson(target)); assertThat(gson.toJson(target)).isEqualTo("[\"Hello\",\"World\"]");
} }
@Test @Test
public void testArrayOfStringsDeserialization() { public void testArrayOfStringsDeserialization() {
String json = "[\"Hello\",\"World\"]"; String json = "[\"Hello\",\"World\"]";
String[] target = gson.fromJson(json, String[].class); String[] target = gson.fromJson(json, String[].class);
assertEquals("Hello", target[0]); assertThat(target).asList().containsExactly("Hello", "World");
assertEquals("World", target[1]);
} }
@Test @Test
public void testSingleStringArraySerialization() throws Exception { public void testSingleStringArraySerialization() {
String[] s = { "hello" }; String[] s = { "hello" };
String output = gson.toJson(s); String output = gson.toJson(s);
assertEquals("[\"hello\"]", output); assertThat(output).isEqualTo("[\"hello\"]");
} }
@Test @Test
public void testSingleStringArrayDeserialization() throws Exception { public void testSingleStringArrayDeserialization() {
String json = "[\"hello\"]"; String json = "[\"hello\"]";
String[] arrayType = gson.fromJson(json, String[].class); String[] arrayType = gson.fromJson(json, String[].class);
assertEquals(1, arrayType.length); assertThat(arrayType).asList().containsExactly("hello");
assertEquals("hello", arrayType[0]);
} }
@Test @Test
public void testArrayOfCollectionSerialization() throws Exception { public void testArrayOfCollectionSerialization() {
StringBuilder sb = new StringBuilder("["); StringBuilder sb = new StringBuilder("[");
int arraySize = 3; int arraySize = 3;
@ -182,42 +176,42 @@ public class ArrayTest {
sb.append(']'); sb.append(']');
String json = gson.toJson(arrayOfCollection, typeToSerialize); String json = gson.toJson(arrayOfCollection, typeToSerialize);
assertEquals(sb.toString(), json); assertThat(json).isEqualTo(sb.toString());
} }
@Test @Test
public void testArrayOfCollectionDeserialization() throws Exception { public void testArrayOfCollectionDeserialization() {
String json = "[[1,2],[3,4]]"; String json = "[[1,2],[3,4]]";
Type type = new TypeToken<Collection<Integer>[]>() {}.getType(); Type type = new TypeToken<Collection<Integer>[]>() {}.getType();
Collection<Integer>[] target = gson.fromJson(json, type); Collection<Integer>[] target = gson.fromJson(json, type);
assertEquals(2, target.length); assertThat(target.length).isEqualTo(2);
assertArrayEquals(new Integer[] {1, 2}, target[0].toArray(new Integer[0])); assertThat(target[0].toArray(new Integer[0])).isEqualTo(new Integer[] {1, 2});
assertArrayEquals(new Integer[] {3, 4}, target[1].toArray(new Integer[0])); assertThat(target[1].toArray(new Integer[0])).isEqualTo(new Integer[] {3, 4});
} }
@Test @Test
public void testArrayOfPrimitivesAsObjectsSerialization() throws Exception { public void testArrayOfPrimitivesAsObjectsSerialization() {
Object[] objs = new Object[] {1, "abc", 0.3f, 5L}; Object[] objs = new Object[] {1, "abc", 0.3f, 5L};
String json = gson.toJson(objs); String json = gson.toJson(objs);
assertTrue(json.contains("abc")); assertThat(json).contains("abc");
assertTrue(json.contains("0.3")); assertThat(json).contains("0.3");
assertTrue(json.contains("5")); assertThat(json).contains("5");
} }
@Test @Test
public void testArrayOfPrimitivesAsObjectsDeserialization() throws Exception { public void testArrayOfPrimitivesAsObjectsDeserialization() {
String json = "[1,'abc',0.3,1.1,5]"; String json = "[1,'abc',0.3,1.1,5]";
Object[] objs = gson.fromJson(json, Object[].class); Object[] objs = gson.fromJson(json, Object[].class);
assertEquals(1, ((Number)objs[0]).intValue()); assertThat(((Number)objs[0]).intValue()).isEqualTo(1);
assertEquals("abc", objs[1]); assertThat(objs[1]).isEqualTo("abc");
assertEquals(0.3, ((Number)objs[2]).doubleValue(), 0); assertThat(((Number)objs[2]).doubleValue()).isEqualTo(0.3);
assertEquals(new BigDecimal("1.1"), new BigDecimal(objs[3].toString())); assertThat(new BigDecimal(objs[3].toString())).isEqualTo(new BigDecimal("1.1"));
assertEquals(5, ((Number)objs[4]).shortValue()); assertThat(((Number)objs[4]).shortValue()).isEqualTo(5);
} }
@Test @Test
public void testObjectArrayWithNonPrimitivesSerialization() throws Exception { public void testObjectArrayWithNonPrimitivesSerialization() {
ClassWithObjects classWithObjects = new ClassWithObjects(); ClassWithObjects classWithObjects = new ClassWithObjects();
BagOfPrimitives bagOfPrimitives = new BagOfPrimitives(); BagOfPrimitives bagOfPrimitives = new BagOfPrimitives();
String classWithObjectsJson = gson.toJson(classWithObjects); String classWithObjectsJson = gson.toJson(classWithObjects);
@ -226,21 +220,21 @@ public class ArrayTest {
Object[] objects = {classWithObjects, bagOfPrimitives}; Object[] objects = {classWithObjects, bagOfPrimitives};
String json = gson.toJson(objects); String json = gson.toJson(objects);
assertTrue(json.contains(classWithObjectsJson)); assertThat(json).contains(classWithObjectsJson);
assertTrue(json.contains(bagOfPrimitivesJson)); assertThat(json).contains(bagOfPrimitivesJson);
} }
@Test @Test
public void testArrayOfNullSerialization() { public void testArrayOfNullSerialization() {
Object[] array = {null}; Object[] array = {null};
String json = gson.toJson(array); String json = gson.toJson(array);
assertEquals("[null]", json); assertThat(json).isEqualTo("[null]");
} }
@Test @Test
public void testArrayOfNullDeserialization() { public void testArrayOfNullDeserialization() {
String[] values = gson.fromJson("[null]", String[].class); String[] values = gson.fromJson("[null]", String[].class);
assertNull(values[0]); assertThat(values[0]).isNull();
} }
/** /**
@ -253,20 +247,20 @@ public class ArrayTest {
{"Alcoa Inc", "29.01", "0.42", "1.47", "4/1 12:00am", "Manufacturing"} {"Alcoa Inc", "29.01", "0.42", "1.47", "4/1 12:00am", "Manufacturing"}
}; };
String json = gson.toJson(items); String json = gson.toJson(items);
assertTrue(json.contains("[[\"3m Co")); assertThat(json).contains("[[\"3m Co");
assertTrue(json.contains("Manufacturing\"]]")); assertThat(json).contains("Manufacturing\"]]");
} }
@Test @Test
public void testMultidimensionalObjectArraysSerialization() { public void testMultidimensionalObjectArraysSerialization() {
Object[][] array = {new Object[] { 1, 2 }}; Object[][] array = {new Object[] { 1, 2 }};
assertEquals("[[1,2]]", gson.toJson(array)); assertThat(gson.toJson(array)).isEqualTo("[[1,2]]");
} }
@Test @Test
public void testMultidimensionalPrimitiveArraysSerialization() { public void testMultidimensionalPrimitiveArraysSerialization() {
int[][] array = {{1, 2}, {3, 4}}; 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 +269,7 @@ public class ArrayTest {
@Test @Test
public void testMixingTypesInObjectArraySerialization() { public void testMixingTypesInObjectArraySerialization() {
Object[] array = {1, 2, new Object[] {"one", "two", 3}}; 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 +280,15 @@ public class ArrayTest {
String json = "[['3m Co','71.72','0.02','0.03','4/2 12:00am','Manufacturing']," 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']]"; + "['Alcoa Inc','29.01','0.42','1.47','4/1 12:00am','Manufacturing']]";
String[][] items = gson.fromJson(json, String[][].class); String[][] items = gson.fromJson(json, String[][].class);
assertEquals("3m Co", items[0][0]); assertThat(items[0][0]).isEqualTo("3m Co");
assertEquals("Manufacturing", items[1][5]); assertThat(items[1][5]).isEqualTo("Manufacturing");
} }
@Test @Test
public void testMultidimensionalPrimitiveArraysDeserialization() { public void testMultidimensionalPrimitiveArraysDeserialization() {
String json = "[[1,2],[3,4]]"; String json = "[[1,2],[3,4]]";
int[][] expected = {{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 */ /** http://code.google.com/p/google-gson/issues/detail?id=342 */
@ -304,7 +298,6 @@ public class ArrayTest {
new String[] {"test1", "test2"}, new String[] {"test1", "test2"},
new String[] {"test3", "test4"} new String[] {"test3", "test4"}
}; };
assertEquals("[[\"test1\",\"test2\"],[\"test3\",\"test4\"]]", assertThat(new Gson().toJson(stringArrays)).isEqualTo("[[\"test1\",\"test2\"],[\"test3\",\"test4\"]]");
new Gson().toJson(stringArrays));
} }
} }

View File

@ -15,9 +15,7 @@
*/ */
package com.google.gson.functional; package com.google.gson.functional;
import static org.junit.Assert.assertEquals; import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import com.google.gson.Gson; import com.google.gson.Gson;
@ -48,7 +46,7 @@ public class CircularReferenceTest {
} }
@Test @Test
public void testCircularSerialization() throws Exception { public void testCircularSerialization() {
ContainsReferenceToSelfType a = new ContainsReferenceToSelfType(); ContainsReferenceToSelfType a = new ContainsReferenceToSelfType();
ContainsReferenceToSelfType b = new ContainsReferenceToSelfType(); ContainsReferenceToSelfType b = new ContainsReferenceToSelfType();
a.children.add(b); a.children.add(b);
@ -61,16 +59,16 @@ public class CircularReferenceTest {
} }
@Test @Test
public void testSelfReferenceIgnoredInSerialization() throws Exception { public void testSelfReferenceIgnoredInSerialization() {
ClassOverridingEquals objA = new ClassOverridingEquals(); ClassOverridingEquals objA = new ClassOverridingEquals();
objA.ref = objA; objA.ref = objA;
String json = gson.toJson(objA); String json = gson.toJson(objA);
assertFalse(json.contains("ref")); // self-reference is ignored assertThat(json).doesNotContain("ref"); // self-reference is ignored
} }
@Test @Test
public void testSelfReferenceArrayFieldSerialization() throws Exception { public void testSelfReferenceArrayFieldSerialization() {
ClassWithSelfReferenceArray objA = new ClassWithSelfReferenceArray(); ClassWithSelfReferenceArray objA = new ClassWithSelfReferenceArray();
objA.children = new ClassWithSelfReferenceArray[]{objA}; objA.children = new ClassWithSelfReferenceArray[]{objA};
@ -82,7 +80,7 @@ public class CircularReferenceTest {
} }
@Test @Test
public void testSelfReferenceCustomHandlerSerialization() throws Exception { public void testSelfReferenceCustomHandlerSerialization() {
ClassWithSelfReference obj = new ClassWithSelfReference(); ClassWithSelfReference obj = new ClassWithSelfReference();
obj.child = obj; obj.child = obj;
Gson gson = new GsonBuilder().registerTypeAdapter(ClassWithSelfReference.class, new JsonSerializer<ClassWithSelfReference>() { Gson gson = new GsonBuilder().registerTypeAdapter(ClassWithSelfReference.class, new JsonSerializer<ClassWithSelfReference>() {
@ -102,22 +100,22 @@ public class CircularReferenceTest {
} }
@Test @Test
public void testDirectedAcyclicGraphSerialization() throws Exception { public void testDirectedAcyclicGraphSerialization() {
ContainsReferenceToSelfType a = new ContainsReferenceToSelfType(); ContainsReferenceToSelfType a = new ContainsReferenceToSelfType();
ContainsReferenceToSelfType b = new ContainsReferenceToSelfType(); ContainsReferenceToSelfType b = new ContainsReferenceToSelfType();
ContainsReferenceToSelfType c = new ContainsReferenceToSelfType(); ContainsReferenceToSelfType c = new ContainsReferenceToSelfType();
a.children.add(b); a.children.add(b);
a.children.add(c); a.children.add(c);
b.children.add(c); b.children.add(c);
assertNotNull(gson.toJson(a)); assertThat(gson.toJson(a)).isNotNull();
} }
@Test @Test
public void testDirectedAcyclicGraphDeserialization() throws Exception { public void testDirectedAcyclicGraphDeserialization() {
String json = "{\"children\":[{\"children\":[{\"children\":[]}]},{\"children\":[]}]}"; String json = "{\"children\":[{\"children\":[{\"children\":[]}]},{\"children\":[]}]}";
ContainsReferenceToSelfType target = gson.fromJson(json, ContainsReferenceToSelfType.class); ContainsReferenceToSelfType target = gson.fromJson(json, ContainsReferenceToSelfType.class);
assertNotNull(target); assertThat(target).isNotNull();
assertEquals(2, target.children.size()); assertThat(target.children).hasSize(2);
} }
private static class ContainsReferenceToSelfType { private static class ContainsReferenceToSelfType {

View File

@ -16,10 +16,7 @@
package com.google.gson.functional; package com.google.gson.functional;
import static org.junit.Assert.assertArrayEquals; import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;
@ -65,7 +62,7 @@ public class CollectionTest {
Collection<Integer> target = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9); Collection<Integer> target = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
Type targetType = new TypeToken<Collection<Integer>>() {}.getType(); Type targetType = new TypeToken<Collection<Integer>>() {}.getType();
String json = gson.toJson(target, targetType); 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 @Test
@ -74,11 +71,11 @@ public class CollectionTest {
Type collectionType = new TypeToken<Collection<Integer>>() { }.getType(); Type collectionType = new TypeToken<Collection<Integer>>() { }.getType();
Collection<Integer> target = gson.fromJson(json, collectionType); Collection<Integer> target = gson.fromJson(json, collectionType);
int[] expected = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; int[] expected = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
assertArrayEquals(expected, toIntArray(target)); assertThat(toIntArray(target)).isEqualTo(expected);
} }
@Test @Test
public void testTopLevelListOfIntegerCollectionsDeserialization() throws Exception { public void testTopLevelListOfIntegerCollectionsDeserialization() {
String json = "[[1,2,3],[4,5,6],[7,8,9]]"; String json = "[[1,2,3],[4,5,6],[7,8,9]]";
Type collectionType = new TypeToken<Collection<Collection<Integer>>>() {}.getType(); Type collectionType = new TypeToken<Collection<Collection<Integer>>>() {}.getType();
List<Collection<Integer>> target = gson.fromJson(json, collectionType); List<Collection<Integer>> target = gson.fromJson(json, collectionType);
@ -91,7 +88,7 @@ public class CollectionTest {
} }
for (int i = 0; i < 3; i++) { 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 class CollectionTest {
list.add("a2"); list.add("a2");
Type linkedListType = new TypeToken<LinkedList<String>>() {}.getType(); Type linkedListType = new TypeToken<LinkedList<String>>() {}.getType();
String json = gson.toJson(list, linkedListType); String json = gson.toJson(list, linkedListType);
assertTrue(json.contains("a1")); assertThat(json).contains("a1");
assertTrue(json.contains("a2")); assertThat(json).contains("a2");
} }
@Test @Test
@ -111,8 +108,8 @@ public class CollectionTest {
String json = "['a1','a2']"; String json = "['a1','a2']";
Type linkedListType = new TypeToken<LinkedList<String>>() {}.getType(); Type linkedListType = new TypeToken<LinkedList<String>>() {}.getType();
List<String> list = gson.fromJson(json, linkedListType); List<String> list = gson.fromJson(json, linkedListType);
assertEquals("a1", list.get(0)); assertThat(list.get(0)).isEqualTo("a1");
assertEquals("a2", list.get(1)); assertThat(list.get(1)).isEqualTo("a2");
} }
@Test @Test
@ -122,8 +119,8 @@ public class CollectionTest {
queue.add("a2"); queue.add("a2");
Type queueType = new TypeToken<Queue<String>>() {}.getType(); Type queueType = new TypeToken<Queue<String>>() {}.getType();
String json = gson.toJson(queue, queueType); String json = gson.toJson(queue, queueType);
assertTrue(json.contains("a1")); assertThat(json).contains("a1");
assertTrue(json.contains("a2")); assertThat(json).contains("a2");
} }
@Test @Test
@ -131,45 +128,45 @@ public class CollectionTest {
String json = "['a1','a2']"; String json = "['a1','a2']";
Type queueType = new TypeToken<Queue<String>>() {}.getType(); Type queueType = new TypeToken<Queue<String>>() {}.getType();
Queue<String> queue = gson.fromJson(json, queueType); Queue<String> queue = gson.fromJson(json, queueType);
assertEquals("a1", queue.element()); assertThat(queue.element()).isEqualTo("a1");
queue.remove(); queue.remove();
assertEquals("a2", queue.element()); assertThat(queue.element()).isEqualTo("a2");
} }
@Test @Test
public void testPriorityQueue() throws Exception { public void testPriorityQueue() {
Type type = new TypeToken<PriorityQueue<Integer>>(){}.getType(); Type type = new TypeToken<PriorityQueue<Integer>>(){}.getType();
PriorityQueue<Integer> queue = gson.fromJson("[10, 20, 22]", type); PriorityQueue<Integer> queue = gson.fromJson("[10, 20, 22]", type);
assertEquals(3, queue.size()); assertThat(queue.size()).isEqualTo(3);
String json = gson.toJson(queue); String json = gson.toJson(queue);
assertEquals(10, queue.remove().intValue()); assertThat(queue.remove()).isEqualTo(10);
assertEquals(20, queue.remove().intValue()); assertThat(queue.remove()).isEqualTo(20);
assertEquals(22, queue.remove().intValue()); assertThat(queue.remove()).isEqualTo(22);
assertEquals("[10,20,22]", json); assertThat(json).isEqualTo("[10,20,22]");
} }
@Test @Test
public void testVector() { public void testVector() {
Type type = new TypeToken<Vector<Integer>>(){}.getType(); Type type = new TypeToken<Vector<Integer>>(){}.getType();
Vector<Integer> target = gson.fromJson("[10, 20, 31]", type); Vector<Integer> target = gson.fromJson("[10, 20, 31]", type);
assertEquals(3, target.size()); assertThat(target.size()).isEqualTo(3);
assertEquals(10, target.get(0).intValue()); assertThat(target.get(0)).isEqualTo(10);
assertEquals(20, target.get(1).intValue()); assertThat(target.get(1)).isEqualTo(20);
assertEquals(31, target.get(2).intValue()); assertThat(target.get(2)).isEqualTo(31);
String json = gson.toJson(target); String json = gson.toJson(target);
assertEquals("[10,20,31]", json); assertThat(json).isEqualTo("[10,20,31]");
} }
@Test @Test
public void testStack() { public void testStack() {
Type type = new TypeToken<Stack<Integer>>(){}.getType(); Type type = new TypeToken<Stack<Integer>>(){}.getType();
Stack<Integer> target = gson.fromJson("[11, 13, 17]", type); Stack<Integer> target = gson.fromJson("[11, 13, 17]", type);
assertEquals(3, target.size()); assertThat(target.size()).isEqualTo(3);
String json = gson.toJson(target); String json = gson.toJson(target);
assertEquals(17, target.pop().intValue()); assertThat(target.pop()).isEqualTo(17);
assertEquals(13, target.pop().intValue()); assertThat(target.pop()).isEqualTo(13);
assertEquals(11, target.pop().intValue()); assertThat(target.pop()).isEqualTo(11);
assertEquals("[11,13,17]", json); assertThat(json).isEqualTo("[11,13,17]");
} }
@Test @Test
@ -181,7 +178,7 @@ public class CollectionTest {
String expected = "[\"foo\",null,\"bar\"]"; String expected = "[\"foo\",null,\"bar\"]";
Type typeOfList = new TypeToken<List<String>>() {}.getType(); Type typeOfList = new TypeToken<List<String>>() {}.getType();
String json = gson.toJson(list, typeOfList); String json = gson.toJson(list, typeOfList);
assertEquals(expected, json); assertThat(json).isEqualTo(expected);
} }
@Test @Test
@ -194,7 +191,7 @@ public class CollectionTest {
Type expectedType = new TypeToken<List<String>>() {}.getType(); Type expectedType = new TypeToken<List<String>>() {}.getType();
List<String> target = gson.fromJson(json, expectedType); List<String> target = gson.fromJson(json, expectedType);
for (int i = 0; i < expected.size(); ++i) { 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 class CollectionTest {
List<Object> target = new ArrayList<>(); List<Object> target = new ArrayList<>();
target.add("Hello"); target.add("Hello");
target.add("World"); target.add("World");
assertEquals("[\"Hello\",\"World\"]", gson.toJson(target)); assertThat(gson.toJson(target)).isEqualTo("[\"Hello\",\"World\"]");
Type type = new TypeToken<List<Object>>() {}.getType(); Type type = new TypeToken<List<Object>>() {}.getType();
assertEquals("[\"Hello\",\"World\"]", gson.toJson(target, type)); assertThat(gson.toJson(target, type)).isEqualTo("[\"Hello\",\"World\"]");
} }
@Test @Test
@ -215,10 +212,10 @@ public class CollectionTest {
target.add("Hello"); target.add("Hello");
target.add(null); target.add(null);
target.add("World"); target.add("World");
assertEquals("[\"Hello\",null,\"World\"]", gson.toJson(target)); assertThat(gson.toJson(target)).isEqualTo("[\"Hello\",null,\"World\"]");
Type type = new TypeToken<List<Object>>() {}.getType(); Type type = new TypeToken<List<Object>>() {}.getType();
assertEquals("[\"Hello\",null,\"World\"]", gson.toJson(target, type)); assertThat(gson.toJson(target, type)).isEqualTo("[\"Hello\",null,\"World\"]");
} }
@Test @Test
@ -226,7 +223,7 @@ public class CollectionTest {
List<String> target = new ArrayList<>(); List<String> target = new ArrayList<>();
target.add("Hello"); target.add("Hello");
target.add("World"); target.add("World");
assertEquals("[\"Hello\",\"World\"]", gson.toJson(target)); assertThat(gson.toJson(target)).isEqualTo("[\"Hello\",\"World\"]");
} }
@Test @Test
@ -238,10 +235,10 @@ public class CollectionTest {
target.add(objB); target.add(objB);
String result = gson.toJson(target); String result = gson.toJson(target);
assertTrue(result.startsWith("[")); assertThat(result.startsWith("[")).isTrue();
assertTrue(result.endsWith("]")); assertThat(result.endsWith("]")).isTrue();
for (BagOfPrimitives obj : target) { for (BagOfPrimitives obj : target) {
assertTrue(result.contains(obj.getExpectedJson())); assertThat(result).contains(obj.getExpectedJson());
} }
} }
@ -251,14 +248,13 @@ public class CollectionTest {
Type collectionType = new TypeToken<Collection<String>>() { }.getType(); Type collectionType = new TypeToken<Collection<String>>() { }.getType();
Collection<String> target = gson.fromJson(json, collectionType); Collection<String> target = gson.fromJson(json, collectionType);
assertTrue(target.contains("Hello")); assertThat(target).containsExactly("Hello", "World").inOrder();
assertTrue(target.contains("World"));
} }
@Test @Test
public void testRawCollectionOfIntegersSerialization() { public void testRawCollectionOfIntegersSerialization() {
Collection<Integer> target = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9); Collection<Integer> 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 @Test
@ -266,7 +262,7 @@ public class CollectionTest {
BagOfPrimitives bag1 = new BagOfPrimitives(); BagOfPrimitives bag1 = new BagOfPrimitives();
Collection<?> target = Arrays.asList(bag1, bag1, "test"); Collection<?> target = Arrays.asList(bag1, bag1, "test");
String json = gson.toJson(target); String json = gson.toJson(target);
assertTrue(json.contains(bag1.getExpectedJson())); assertThat(json).contains(bag1.getExpectedJson());
} }
@Test @Test
@ -274,12 +270,11 @@ public class CollectionTest {
String json = "[0,1,2,3,4,5,6,7,8,9]"; String json = "[0,1,2,3,4,5,6,7,8,9]";
Collection<?> integers = gson.fromJson(json, Collection.class); Collection<?> integers = gson.fromJson(json, Collection.class);
// JsonReader converts numbers to double by default so we need a floating point comparison // 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\"]"; json = "[\"Hello\", \"World\"]";
Collection<?> strings = gson.fromJson(json, Collection.class); Collection<?> strings = gson.fromJson(json, Collection.class);
assertTrue(strings.contains("Hello")); assertThat(strings).containsExactly("Hello", "World").inOrder();
assertTrue(strings.contains("World"));
} }
@Test @Test
@ -287,40 +282,40 @@ public class CollectionTest {
BagOfPrimitives bag = new BagOfPrimitives(10, 20, false, "stringValue"); BagOfPrimitives bag = new BagOfPrimitives(10, 20, false, "stringValue");
String json = '[' + bag.getExpectedJson() + ',' + bag.getExpectedJson() + ']'; String json = '[' + bag.getExpectedJson() + ',' + bag.getExpectedJson() + ']';
Collection<?> target = gson.fromJson(json, Collection.class); Collection<?> target = gson.fromJson(json, Collection.class);
assertEquals(2, target.size()); assertThat(target.size()).isEqualTo(2);
for (Object bag1 : target) { for (Object bag1 : target) {
// Gson 2.0 converts raw objects into maps // Gson 2.0 converts raw objects into maps
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
Map<String, Object> values = (Map<String, Object>) bag1; Map<String, Object> values = (Map<String, Object>) bag1;
assertTrue(values.containsValue(10.0)); assertThat(values.containsValue(10.0)).isTrue();
assertTrue(values.containsValue(20.0)); assertThat(values.containsValue(20.0)).isTrue();
assertTrue(values.containsValue("stringValue")); assertThat(values.containsValue("stringValue")).isTrue();
} }
} }
@Test @Test
public void testWildcardPrimitiveCollectionSerilaization() throws Exception { public void testWildcardPrimitiveCollectionSerilaization() {
Collection<? extends Integer> target = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9); Collection<? extends Integer> target = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
Type collectionType = new TypeToken<Collection<? extends Integer>>() { }.getType(); Type collectionType = new TypeToken<Collection<? extends Integer>>() { }.getType();
String json = gson.toJson(target, collectionType); 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); 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 @Test
public void testWildcardPrimitiveCollectionDeserilaization() throws Exception { public void testWildcardPrimitiveCollectionDeserilaization() {
String json = "[1,2,3,4,5,6,7,8,9]"; String json = "[1,2,3,4,5,6,7,8,9]";
Type collectionType = new TypeToken<Collection<? extends Integer>>() { }.getType(); Type collectionType = new TypeToken<Collection<? extends Integer>>() { }.getType();
Collection<? extends Integer> target = gson.fromJson(json, collectionType); Collection<? extends Integer> target = gson.fromJson(json, collectionType);
assertEquals(9, target.size()); assertThat(target.size()).isEqualTo(9);
assertTrue(target.contains(1)); assertThat(target).contains(1);
assertTrue(target.contains(9)); assertThat(target).contains(2);
} }
@Test @Test
public void testWildcardCollectionField() throws Exception { public void testWildcardCollectionField() {
Collection<BagOfPrimitives> collection = new ArrayList<>(); Collection<BagOfPrimitives> collection = new ArrayList<>();
BagOfPrimitives objA = new BagOfPrimitives(3L, 1, true, "blah"); BagOfPrimitives objA = new BagOfPrimitives(3L, 1, true, "blah");
BagOfPrimitives objB = new BagOfPrimitives(2L, 6, false, "blahB"); BagOfPrimitives objB = new BagOfPrimitives(2L, 6, false, "blahB");
@ -329,14 +324,14 @@ public class CollectionTest {
ObjectWithWildcardCollection target = new ObjectWithWildcardCollection(collection); ObjectWithWildcardCollection target = new ObjectWithWildcardCollection(collection);
String json = gson.toJson(target); String json = gson.toJson(target);
assertTrue(json.contains(objA.getExpectedJson())); assertThat(json).contains(objA.getExpectedJson());
assertTrue(json.contains(objB.getExpectedJson())); assertThat(json).contains(objB.getExpectedJson());
target = gson.fromJson(json, ObjectWithWildcardCollection.class); target = gson.fromJson(json, ObjectWithWildcardCollection.class);
Collection<? extends BagOfPrimitives> deserializedCollection = target.getCollection(); Collection<? extends BagOfPrimitives> deserializedCollection = target.getCollection();
assertEquals(2, deserializedCollection.size()); assertThat(deserializedCollection.size()).isEqualTo(2);
assertTrue(deserializedCollection.contains(objA)); assertThat(deserializedCollection).contains(objA);
assertTrue(deserializedCollection.contains(objB)); assertThat(deserializedCollection).contains(objB);
} }
@Test @Test
@ -345,9 +340,9 @@ public class CollectionTest {
object.longs.add(1L); object.longs.add(1L);
object.longs.add(3L); object.longs.add(3L);
String json = gson.toJson(object, HasArrayListField.class); 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); 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 @Test
@ -362,7 +357,7 @@ public class CollectionTest {
Gson gson = new GsonBuilder() Gson gson = new GsonBuilder()
.registerTypeAdapter(listOfString, stringListSerializer) .registerTypeAdapter(listOfString, stringListSerializer)
.create(); .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 { static class HasArrayListField {
@ -375,7 +370,7 @@ public class CollectionTest {
for (Iterator<?> iterator = collection.iterator(); iterator.hasNext(); ++i) { for (Iterator<?> iterator = collection.iterator(); iterator.hasNext(); ++i) {
Object obj = iterator.next(); Object obj = iterator.next();
if (obj instanceof Integer) { if (obj instanceof Integer) {
ints[i] = ((Integer)obj).intValue(); ints[i] = (Integer) obj;
} else if (obj instanceof Long) { } else if (obj instanceof Long) {
ints[i] = ((Long)obj).intValue(); ints[i] = ((Long)obj).intValue();
} }
@ -407,17 +402,17 @@ public class CollectionTest {
set.add(new Entry(1)); set.add(new Entry(1));
set.add(new Entry(2)); set.add(new Entry(2));
String json = gson.toJson(set); String json = gson.toJson(set);
assertTrue(json.contains("1")); assertThat(json).contains("1");
assertTrue(json.contains("2")); assertThat(json).contains("2");
} }
@Test @Test
public void testSetDeserialization() { public void testSetDeserialization() {
String json = "[{value:1},{value:2}]"; String json = "[{value:1},{value:2}]";
Type type = new TypeToken<Set<Entry>>() {}.getType(); Type type = new TypeToken<Set<Entry>>() {}.getType();
Set<Entry> set = gson.fromJson(json, type); Set<Entry> set = gson.fromJson(json, type);
assertEquals(2, set.size()); assertThat(set.size()).isEqualTo(2);
for (Entry entry : set) { for (Entry entry : set) {
assertTrue(entry.value == 1 || entry.value == 2); assertThat(entry.value).isAnyOf(1, 2);
} }
} }
@ -436,8 +431,8 @@ public class CollectionTest {
"}"; "}";
BigClass bigClass = new Gson().fromJson(json, BigClass.class); BigClass bigClass = new Gson().fromJson(json, BigClass.class);
SmallClass small = bigClass.inBig.get("key").get(0); SmallClass small = bigClass.inBig.get("key").get(0);
assertNotNull(small); assertThat(small).isNotNull();
assertEquals("hello", small.inSmall); assertThat(small.inSmall).isEqualTo("hello");
} }
} }

View File

@ -15,7 +15,7 @@
*/ */
package com.google.gson.functional; 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 com.google.gson.Gson;
import java.util.concurrent.CountDownLatch; import java.util.concurrent.CountDownLatch;
@ -91,7 +91,7 @@ public class ConcurrencyTest {
} }
startLatch.countDown(); startLatch.countDown();
finishedLatch.await(); finishedLatch.await();
assertFalse(failed.get()); assertThat(failed.get()).isFalse();
} }
/** /**
@ -122,7 +122,7 @@ public class ConcurrencyTest {
} }
startLatch.countDown(); startLatch.countDown();
finishedLatch.await(); finishedLatch.await();
assertFalse(failed.get()); assertThat(failed.get()).isFalse();
} }
@SuppressWarnings("unused") @SuppressWarnings("unused")

View File

@ -16,8 +16,7 @@
package com.google.gson.functional; package com.google.gson.functional;
import static org.junit.Assert.assertEquals; import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertNull;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;
@ -50,21 +49,21 @@ public class CustomDeserializerTest {
} }
@Test @Test
public void testDefaultConstructorNotCalledOnObject() throws Exception { public void testDefaultConstructorNotCalledOnObject() {
DataHolder data = new DataHolder(DEFAULT_VALUE); DataHolder data = new DataHolder(DEFAULT_VALUE);
String json = gson.toJson(data); String json = gson.toJson(data);
DataHolder actual = gson.fromJson(json, DataHolder.class); DataHolder actual = gson.fromJson(json, DataHolder.class);
assertEquals(DEFAULT_VALUE + SUFFIX, actual.getData()); assertThat(actual.getData()).isEqualTo(DEFAULT_VALUE + SUFFIX);
} }
@Test @Test
public void testDefaultConstructorNotCalledOnField() throws Exception { public void testDefaultConstructorNotCalledOnField() {
DataHolderWrapper dataWrapper = new DataHolderWrapper(new DataHolder(DEFAULT_VALUE)); DataHolderWrapper dataWrapper = new DataHolderWrapper(new DataHolder(DEFAULT_VALUE));
String json = gson.toJson(dataWrapper); String json = gson.toJson(dataWrapper);
DataHolderWrapper actual = gson.fromJson(json, DataHolderWrapper.class); 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 { private static class DataHolder {
@ -124,7 +123,7 @@ public class CustomDeserializerTest {
} }
}).create(); }).create();
SubType1 target = (SubType1) gson.fromJson(json, MyBase.class); SubType1 target = (SubType1) gson.fromJson(json, MyBase.class);
assertEquals("abc", target.field1); assertThat(target.field1).isEqualTo("abc");
} }
private static class MyBase { private static class MyBase {
@ -164,7 +163,7 @@ public class CustomDeserializerTest {
}).create(); }).create();
String json = "{baseName:'Base',subName:'SubRevised'}"; String json = "{baseName:'Base',subName:'SubRevised'}";
Base target = gson.fromJson(json, Base.class); Base target = gson.fromJson(json, Base.class);
assertNull(target); assertThat(target).isNull();
} }
@Test @Test
@ -179,7 +178,7 @@ public class CustomDeserializerTest {
}).create(); }).create();
String json = "{base:{baseName:'Base',subName:'SubRevised'}}"; String json = "{base:{baseName:'Base',subName:'SubRevised'}}";
ClassWithBaseField target = gson.fromJson(json, ClassWithBaseField.class); ClassWithBaseField target = gson.fromJson(json, ClassWithBaseField.class);
assertNull(target.base); assertThat(target.base).isNull();
} }
@Test @Test
@ -194,8 +193,8 @@ public class CustomDeserializerTest {
}).create(); }).create();
String json = "[{baseName:'Base'},{baseName:'Base'}]"; String json = "[{baseName:'Base'},{baseName:'Base'}]";
Base[] target = gson.fromJson(json, Base[].class); Base[] target = gson.fromJson(json, Base[].class);
assertNull(target[0]); assertThat(target[0]).isNull();
assertNull(target[1]); assertThat(target[1]).isNull();
} }
@Test @Test
@ -210,8 +209,8 @@ public class CustomDeserializerTest {
}).create(); }).create();
String json = "{bases:[{baseName:'Base'},{baseName:'Base'}]}"; String json = "{bases:[{baseName:'Base'},{baseName:'Base'}]}";
ClassWithBaseArray target = gson.fromJson(json, ClassWithBaseArray.class); ClassWithBaseArray target = gson.fromJson(json, ClassWithBaseArray.class);
assertNull(target.bases[0]); assertThat(target.bases[0]).isNull();
assertNull(target.bases[1]); assertThat(target.bases[1]).isNull();
} }
private static final class ClassWithBaseArray { private static final class ClassWithBaseArray {

View File

@ -16,8 +16,7 @@
package com.google.gson.functional; package com.google.gson.functional;
import static org.junit.Assert.assertEquals; import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertTrue;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;
@ -52,7 +51,7 @@ public class CustomSerializerTest {
ClassWithBaseField target = new ClassWithBaseField(new Base()); ClassWithBaseField target = new ClassWithBaseField(new Base());
JsonObject json = (JsonObject) gson.toJsonTree(target); JsonObject json = (JsonObject) gson.toJsonTree(target);
JsonObject base = json.get("base").getAsJsonObject(); 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 @Test
@ -64,7 +63,7 @@ public class CustomSerializerTest {
ClassWithBaseField target = new ClassWithBaseField(new Sub()); ClassWithBaseField target = new ClassWithBaseField(new Sub());
JsonObject json = (JsonObject) gson.toJsonTree(target); JsonObject json = (JsonObject) gson.toJsonTree(target);
JsonObject base = json.get("base").getAsJsonObject(); 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 @Test
@ -78,7 +77,7 @@ public class CustomSerializerTest {
JsonArray array = json.get("base").getAsJsonArray(); JsonArray array = json.get("base").getAsJsonArray();
for (JsonElement element : array) { for (JsonElement element : array) {
JsonElement serializerKey = element.getAsJsonObject().get(Base.SERIALIZER_KEY); JsonElement serializerKey = element.getAsJsonObject().get(Base.SERIALIZER_KEY);
assertEquals(SubSerializer.NAME, serializerKey.getAsString()); assertThat(serializerKey.getAsString()).isEqualTo(SubSerializer.NAME);
} }
} }
@ -90,7 +89,7 @@ public class CustomSerializerTest {
ClassWithBaseField target = new ClassWithBaseField(new Sub()); ClassWithBaseField target = new ClassWithBaseField(new Sub());
JsonObject json = (JsonObject) gson.toJsonTree(target); JsonObject json = (JsonObject) gson.toJsonTree(target);
JsonObject base = json.get("base").getAsJsonObject(); 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 @Test
@ -103,6 +102,6 @@ public class CustomSerializerTest {
}) })
.create(); .create();
JsonElement json = gson.toJsonTree(new Base()); JsonElement json = gson.toJsonTree(new Base());
assertTrue(json.isJsonNull()); assertThat(json.isJsonNull()).isTrue();
} }
} }

View File

@ -15,10 +15,7 @@
*/ */
package com.google.gson.functional; package com.google.gson.functional;
import static org.junit.Assert.assertEquals; import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;
@ -71,7 +68,7 @@ public class CustomTypeAdaptersTest {
} }
}).create(); }).create();
ClassWithCustomTypeConverter target = new ClassWithCustomTypeConverter(); ClassWithCustomTypeConverter target = new ClassWithCustomTypeConverter();
assertEquals("{\"bag\":5,\"value\":25}", gson.toJson(target)); assertThat(gson.toJson(target)).isEqualTo("{\"bag\":5,\"value\":25}");
} }
@Test @Test
@ -88,7 +85,7 @@ public class CustomTypeAdaptersTest {
}).create(); }).create();
String json = "{\"bag\":5,\"value\":25}"; String json = "{\"bag\":5,\"value\":25}";
ClassWithCustomTypeConverter target = gson.fromJson(json, ClassWithCustomTypeConverter.class); ClassWithCustomTypeConverter target = gson.fromJson(json, ClassWithCustomTypeConverter.class);
assertEquals(5, target.getBag().getIntValue()); assertThat(target.getBag().getIntValue()).isEqualTo(5);
} }
@Test @Test
@ -100,7 +97,7 @@ public class CustomTypeAdaptersTest {
String jsonFromCustomSerializer = gson.toJson(newFooObject); String jsonFromCustomSerializer = gson.toJson(newFooObject);
String jsonFromGson = basicGson.toJson(newFooObject); String jsonFromGson = basicGson.toJson(newFooObject);
assertEquals(jsonFromGson, jsonFromCustomSerializer); assertThat(jsonFromCustomSerializer).isEqualTo(jsonFromGson);
} }
@Test @Test
@ -112,8 +109,8 @@ public class CustomTypeAdaptersTest {
String json = basicGson.toJson(expectedFoo); String json = basicGson.toJson(expectedFoo);
Foo newFooObject = gson.fromJson(json, Foo.class); Foo newFooObject = gson.fromJson(json, Foo.class);
assertEquals(expectedFoo.key, newFooObject.key); assertThat(newFooObject.key).isEqualTo(expectedFoo.key);
assertEquals(expectedFoo.value, newFooObject.value); assertThat(newFooObject.value).isEqualTo(expectedFoo.value);
} }
@Test @Test
@ -126,7 +123,7 @@ public class CustomTypeAdaptersTest {
} }
}).create(); }).create();
ClassWithCustomTypeConverter target = new ClassWithCustomTypeConverter(); ClassWithCustomTypeConverter target = new ClassWithCustomTypeConverter();
assertEquals("{\"bag\":6,\"value\":10}", gson.toJson(target)); assertThat(gson.toJson(target)).isEqualTo("{\"bag\":6,\"value\":10}");
} }
@Test @Test
@ -141,7 +138,7 @@ public class CustomTypeAdaptersTest {
}).create(); }).create();
String json = "{\"bag\":7,\"value\":25}"; String json = "{\"bag\":7,\"value\":25}";
ClassWithCustomTypeConverter target = gson.fromJson(json, ClassWithCustomTypeConverter.class); ClassWithCustomTypeConverter target = gson.fromJson(json, ClassWithCustomTypeConverter.class);
assertEquals(7, target.getBag().getIntValue()); assertThat(target.getBag().getIntValue()).isEqualTo(7);
} }
@Test @Test
@ -156,10 +153,10 @@ public class CustomTypeAdaptersTest {
}).create(); }).create();
Base b = new Base(); Base b = new Base();
String json = gson.toJson(b); String json = gson.toJson(b);
assertTrue(json.contains("value")); assertThat(json).contains("value");
b = new Derived(); b = new Derived();
json = gson.toJson(b); json = gson.toJson(b);
assertTrue(json.contains("derivedValue")); assertThat(json).contains("derivedValue");
} }
@Test @Test
@ -174,11 +171,11 @@ public class CustomTypeAdaptersTest {
}).create(); }).create();
Base b = new Base(); Base b = new Base();
String json = gson.toJson(b); String json = gson.toJson(b);
assertTrue(json.contains("value")); assertThat(json).contains("value");
b = new Derived(); b = new Derived();
json = gson.toJson(b, Base.class); json = gson.toJson(b, Base.class);
assertTrue(json.contains("value")); assertThat(json).contains("value");
assertFalse(json.contains("derivedValue")); assertThat(json).doesNotContain("derivedValue");
} }
private static class Base { private static class Base {
@ -231,8 +228,8 @@ public class CustomTypeAdaptersTest {
} }
}) })
.create(); .create();
assertEquals("1", gson.toJson(true, boolean.class)); assertThat(gson.toJson(true, boolean.class)).isEqualTo("1");
assertEquals("true", gson.toJson(true, Boolean.class)); assertThat(gson.toJson(true, Boolean.class)).isEqualTo("true");
} }
@Test @Test
@ -245,8 +242,8 @@ public class CustomTypeAdaptersTest {
} }
}) })
.create(); .create();
assertEquals(Boolean.TRUE, gson.fromJson("1", boolean.class)); assertThat(gson.fromJson("1", boolean.class)).isEqualTo(Boolean.TRUE);
assertEquals(Boolean.TRUE, gson.fromJson("true", Boolean.class)); assertThat(gson.fromJson("true", Boolean.class)).isEqualTo(Boolean.TRUE);
} }
@Test @Test
@ -263,7 +260,7 @@ public class CustomTypeAdaptersTest {
}).create(); }).create();
byte[] data = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; byte[] data = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
String json = gson.toJson(data); String json = gson.toJson(data);
assertEquals("\"0123456789\"", json); assertThat(json).isEqualTo("\"0123456789\"");
} }
@Test @Test
@ -285,7 +282,7 @@ public class CustomTypeAdaptersTest {
byte[] actual = gson.fromJson(json, byte[].class); byte[] actual = gson.fromJson(json, byte[].class);
byte[] expected = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; byte[] expected = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
for (int i = 0; i < actual.length; ++i) { for (int i = 0; i < actual.length; ++i) {
assertEquals(expected[i], actual[i]); assertThat(actual[i]).isEqualTo(expected[i]);
} }
} }
@ -335,7 +332,7 @@ public class CustomTypeAdaptersTest {
Set<StringHolder> setOfHolders = new HashSet<>(); Set<StringHolder> setOfHolders = new HashSet<>();
setOfHolders.add(holder); setOfHolders.add(holder);
String json = gson.toJson(setOfHolders, setType); String json = gson.toJson(setOfHolders, setType);
assertTrue(json.contains("Jacob:Tomaw")); assertThat(json).contains("Jacob:Tomaw");
} }
// Test created from Issue 70 // Test created from Issue 70
@ -348,7 +345,7 @@ public class CustomTypeAdaptersTest {
Set<StringHolder> setOfHolders = new HashSet<>(); Set<StringHolder> setOfHolders = new HashSet<>();
setOfHolders.add(holder); setOfHolders.add(holder);
String json = gson.toJson(setOfHolders); String json = gson.toJson(setOfHolders);
assertTrue(json.contains("Jacob:Tomaw")); assertThat(json).contains("Jacob:Tomaw");
} }
// Test created from Issue 70 // Test created from Issue 70
@ -359,10 +356,10 @@ public class CustomTypeAdaptersTest {
.create(); .create();
Type setType = new TypeToken<Set<StringHolder>>() {}.getType(); Type setType = new TypeToken<Set<StringHolder>>() {}.getType();
Set<StringHolder> setOfHolders = gson.fromJson("['Jacob:Tomaw']", setType); Set<StringHolder> setOfHolders = gson.fromJson("['Jacob:Tomaw']", setType);
assertEquals(1, setOfHolders.size()); assertThat(setOfHolders.size()).isEqualTo(1);
StringHolder foo = setOfHolders.iterator().next(); StringHolder foo = setOfHolders.iterator().next();
assertEquals("Jacob", foo.part1); assertThat(foo.part1).isEqualTo("Jacob");
assertEquals("Tomaw", foo.part2); assertThat(foo.part2).isEqualTo("Tomaw");
} }
// Test created from Issue 70 // Test created from Issue 70
@ -376,7 +373,7 @@ public class CustomTypeAdaptersTest {
Map<String, StringHolder> mapOfHolders = new HashMap<>(); Map<String, StringHolder> mapOfHolders = new HashMap<>();
mapOfHolders.put("foo", holder); mapOfHolders.put("foo", holder);
String json = gson.toJson(mapOfHolders, mapType); String json = gson.toJson(mapOfHolders, mapType);
assertTrue(json.contains("\"foo\":\"Jacob:Tomaw\"")); assertThat(json).contains("\"foo\":\"Jacob:Tomaw\"");
} }
// Test created from Issue 70 // Test created from Issue 70
@ -389,7 +386,7 @@ public class CustomTypeAdaptersTest {
Map<String, StringHolder> mapOfHolders = new HashMap<>(); Map<String, StringHolder> mapOfHolders = new HashMap<>();
mapOfHolders.put("foo", holder); mapOfHolders.put("foo", holder);
String json = gson.toJson(mapOfHolders); String json = gson.toJson(mapOfHolders);
assertTrue(json.contains("\"foo\":\"Jacob:Tomaw\"")); assertThat(json).contains("\"foo\":\"Jacob:Tomaw\"");
} }
// Test created from Issue 70 // Test created from Issue 70
@ -400,10 +397,10 @@ public class CustomTypeAdaptersTest {
.create(); .create();
Type mapType = new TypeToken<Map<String, StringHolder>>() {}.getType(); Type mapType = new TypeToken<Map<String, StringHolder>>() {}.getType();
Map<String, StringHolder> mapOfFoo = gson.fromJson("{'foo':'Jacob:Tomaw'}", mapType); Map<String, StringHolder> mapOfFoo = gson.fromJson("{'foo':'Jacob:Tomaw'}", mapType);
assertEquals(1, mapOfFoo.size()); assertThat(mapOfFoo.size()).isEqualTo(1);
StringHolder foo = mapOfFoo.get("foo"); StringHolder foo = mapOfFoo.get("foo");
assertEquals("Jacob", foo.part1); assertThat(foo.part1).isEqualTo("Jacob");
assertEquals("Tomaw", foo.part2); assertThat(foo.part2).isEqualTo("Tomaw");
} }
@Test @Test
@ -413,7 +410,7 @@ public class CustomTypeAdaptersTest {
.create(); .create();
DataHolderWrapper target = new DataHolderWrapper(new DataHolder("abc")); DataHolderWrapper target = new DataHolderWrapper(new DataHolder("abc"));
String json = gson.toJson(target); String json = gson.toJson(target);
assertEquals("{\"wrappedData\":{\"myData\":\"abc\"}}", json); assertThat(json).isEqualTo("{\"wrappedData\":{\"myData\":\"abc\"}}");
} }
@Test @Test
@ -423,7 +420,7 @@ public class CustomTypeAdaptersTest {
.create(); .create();
String json = "{wrappedData:null}"; String json = "{wrappedData:null}";
DataHolderWrapper actual = gson.fromJson(json, DataHolderWrapper.class); DataHolderWrapper actual = gson.fromJson(json, DataHolderWrapper.class);
assertNull(actual.wrappedData); assertThat(actual.wrappedData).isNull();
} }
// Test created from Issue 352 // Test created from Issue 352
@ -432,10 +429,10 @@ public class CustomTypeAdaptersTest {
Gson gson = new GsonBuilder() Gson gson = new GsonBuilder()
.registerTypeHierarchyAdapter(Date.class, new DateTypeAdapter()) .registerTypeHierarchyAdapter(Date.class, new DateTypeAdapter())
.create(); .create();
assertEquals("0", gson.toJson(new Date(0))); assertThat(gson.toJson(new Date(0))).isEqualTo("0");
assertEquals("0", gson.toJson(new java.sql.Date(0))); assertThat(gson.toJson(new java.sql.Date(0))).isEqualTo("0");
assertEquals(new Date(0), gson.fromJson("0", Date.class)); assertThat(gson.fromJson("0", Date.class)).isEqualTo(new Date(0));
assertEquals(new java.sql.Date(0), gson.fromJson("0", java.sql.Date.class)); assertThat(gson.fromJson("0", java.sql.Date.class)).isEqualTo(new java.sql.Date(0));
} }
private static class DataHolder { private static class DataHolder {

View File

@ -15,9 +15,7 @@
*/ */
package com.google.gson.functional; package com.google.gson.functional;
import static org.junit.Assert.assertEquals; import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import com.google.gson.Gson; import com.google.gson.Gson;
@ -85,7 +83,7 @@ public class DefaultTypeAdaptersTest {
} }
@After @After
public void tearDown() throws Exception { public void tearDown() {
TimeZone.setDefault(oldTimeZone); TimeZone.setDefault(oldTimeZone);
Locale.setDefault(oldLocale); Locale.setDefault(oldLocale);
} }
@ -99,7 +97,7 @@ public class DefaultTypeAdaptersTest {
} }
// Override with a custom type adapter for class. // Override with a custom type adapter for class.
gson = new GsonBuilder().registerTypeAdapter(Class.class, new MyClassTypeAdapter()).create(); 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 @Test
@ -111,14 +109,14 @@ public class DefaultTypeAdaptersTest {
} }
// Override with a custom type adapter for class. // Override with a custom type adapter for class.
gson = new GsonBuilder().registerTypeAdapter(Class.class, new MyClassTypeAdapter()).create(); 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 @Test
public void testUrlSerialization() throws Exception { public void testUrlSerialization() throws Exception {
String urlValue = "http://google.com/"; String urlValue = "http://google.com/";
URL url = new URL(urlValue); URL url = new URL(urlValue);
assertEquals("\"http://google.com/\"", gson.toJson(url)); assertThat(gson.toJson(url)).isEqualTo("\"http://google.com/\"");
} }
@Test @Test
@ -126,23 +124,23 @@ public class DefaultTypeAdaptersTest {
String urlValue = "http://google.com/"; String urlValue = "http://google.com/";
String json = "'http:\\/\\/google.com\\/'"; String json = "'http:\\/\\/google.com\\/'";
URL target = gson.fromJson(json, URL.class); URL target = gson.fromJson(json, URL.class);
assertEquals(urlValue, target.toExternalForm()); assertThat(target.toExternalForm()).isEqualTo(urlValue);
gson.fromJson('"' + urlValue + '"', URL.class); gson.fromJson('"' + urlValue + '"', URL.class);
assertEquals(urlValue, target.toExternalForm()); assertThat(target.toExternalForm()).isEqualTo(urlValue);
} }
@Test @Test
public void testUrlNullSerialization() throws Exception { public void testUrlNullSerialization() {
ClassWithUrlField target = new ClassWithUrlField(); ClassWithUrlField target = new ClassWithUrlField();
assertEquals("{}", gson.toJson(target)); assertThat(gson.toJson(target)).isEqualTo("{}");
} }
@Test @Test
public void testUrlNullDeserialization() { public void testUrlNullDeserialization() {
String json = "{}"; String json = "{}";
ClassWithUrlField target = gson.fromJson(json, ClassWithUrlField.class); ClassWithUrlField target = gson.fromJson(json, ClassWithUrlField.class);
assertNull(target.url); assertThat(target.url).isNull();
} }
private static class ClassWithUrlField { private static class ClassWithUrlField {
@ -153,7 +151,7 @@ public class DefaultTypeAdaptersTest {
public void testUriSerialization() throws Exception { public void testUriSerialization() throws Exception {
String uriValue = "http://google.com/"; String uriValue = "http://google.com/";
URI uri = new URI(uriValue); URI uri = new URI(uriValue);
assertEquals("\"http://google.com/\"", gson.toJson(uri)); assertThat(gson.toJson(uri)).isEqualTo("\"http://google.com/\"");
} }
@Test @Test
@ -161,11 +159,11 @@ public class DefaultTypeAdaptersTest {
String uriValue = "http://google.com/"; String uriValue = "http://google.com/";
String json = '"' + uriValue + '"'; String json = '"' + uriValue + '"';
URI target = gson.fromJson(json, URI.class); URI target = gson.fromJson(json, URI.class);
assertEquals(uriValue, target.toASCIIString()); assertThat(target.toASCIIString()).isEqualTo(uriValue);
} }
@Test @Test
public void testNullSerialization() throws Exception { public void testNullSerialization() {
testNullSerializationAndDeserialization(Boolean.class); testNullSerializationAndDeserialization(Boolean.class);
testNullSerializationAndDeserialization(Byte.class); testNullSerializationAndDeserialization(Byte.class);
testNullSerializationAndDeserialization(Short.class); testNullSerializationAndDeserialization(Short.class);
@ -201,15 +199,15 @@ public class DefaultTypeAdaptersTest {
} }
public static void testNullSerializationAndDeserialization(Gson gson, Class<?> c) { public static void testNullSerializationAndDeserialization(Gson gson, Class<?> c) {
assertEquals("null", gson.toJson(null, c)); assertThat(gson.toJson(null, c)).isEqualTo("null");
assertEquals(null, gson.fromJson("null", c)); assertThat(gson.fromJson("null", c)).isEqualTo(null);
} }
@Test @Test
public void testUuidSerialization() throws Exception { public void testUuidSerialization() {
String uuidValue = "c237bec1-19ef-4858-a98e-521cf0aad4c0"; String uuidValue = "c237bec1-19ef-4858-a98e-521cf0aad4c0";
UUID uuid = UUID.fromString(uuidValue); UUID uuid = UUID.fromString(uuidValue);
assertEquals('"' + uuidValue + '"', gson.toJson(uuid)); assertThat(gson.toJson(uuid)).isEqualTo('"' + uuidValue + '"');
} }
@Test @Test
@ -217,49 +215,49 @@ public class DefaultTypeAdaptersTest {
String uuidValue = "c237bec1-19ef-4858-a98e-521cf0aad4c0"; String uuidValue = "c237bec1-19ef-4858-a98e-521cf0aad4c0";
String json = '"' + uuidValue + '"'; String json = '"' + uuidValue + '"';
UUID target = gson.fromJson(json, UUID.class); UUID target = gson.fromJson(json, UUID.class);
assertEquals(uuidValue, target.toString()); assertThat(target.toString()).isEqualTo(uuidValue);
} }
@Test @Test
public void testLocaleSerializationWithLanguage() { public void testLocaleSerializationWithLanguage() {
Locale target = new Locale("en"); Locale target = new Locale("en");
assertEquals("\"en\"", gson.toJson(target)); assertThat(gson.toJson(target)).isEqualTo("\"en\"");
} }
@Test @Test
public void testLocaleDeserializationWithLanguage() { public void testLocaleDeserializationWithLanguage() {
String json = "\"en\""; String json = "\"en\"";
Locale locale = gson.fromJson(json, Locale.class); Locale locale = gson.fromJson(json, Locale.class);
assertEquals("en", locale.getLanguage()); assertThat(locale.getLanguage()).isEqualTo("en");
} }
@Test @Test
public void testLocaleSerializationWithLanguageCountry() { public void testLocaleSerializationWithLanguageCountry() {
Locale target = Locale.CANADA_FRENCH; Locale target = Locale.CANADA_FRENCH;
assertEquals("\"fr_CA\"", gson.toJson(target)); assertThat(gson.toJson(target)).isEqualTo("\"fr_CA\"");
} }
@Test @Test
public void testLocaleDeserializationWithLanguageCountry() { public void testLocaleDeserializationWithLanguageCountry() {
String json = "\"fr_CA\""; String json = "\"fr_CA\"";
Locale locale = gson.fromJson(json, Locale.class); Locale locale = gson.fromJson(json, Locale.class);
assertEquals(Locale.CANADA_FRENCH, locale); assertThat(locale).isEqualTo(Locale.CANADA_FRENCH);
} }
@Test @Test
public void testLocaleSerializationWithLanguageCountryVariant() { public void testLocaleSerializationWithLanguageCountryVariant() {
Locale target = new Locale("de", "DE", "EURO"); Locale target = new Locale("de", "DE", "EURO");
String json = gson.toJson(target); String json = gson.toJson(target);
assertEquals("\"de_DE_EURO\"", json); assertThat(json).isEqualTo("\"de_DE_EURO\"");
} }
@Test @Test
public void testLocaleDeserializationWithLanguageCountryVariant() { public void testLocaleDeserializationWithLanguageCountryVariant() {
String json = "\"de_DE_EURO\""; String json = "\"de_DE_EURO\"";
Locale locale = gson.fromJson(json, Locale.class); Locale locale = gson.fromJson(json, Locale.class);
assertEquals("de", locale.getLanguage()); assertThat(locale.getLanguage()).isEqualTo("de");
assertEquals("DE", locale.getCountry()); assertThat(locale.getCountry()).isEqualTo("DE");
assertEquals("EURO", locale.getVariant()); assertThat(locale.getVariant()).isEqualTo("EURO");
} }
@Test @Test
@ -267,7 +265,7 @@ public class DefaultTypeAdaptersTest {
ClassWithBigDecimal target = new ClassWithBigDecimal("-122.01e-21"); ClassWithBigDecimal target = new ClassWithBigDecimal("-122.01e-21");
String json = gson.toJson(target); String json = gson.toJson(target);
String actual = json.substring(json.indexOf(':') + 1, json.indexOf('}')); String actual = json.substring(json.indexOf(':') + 1, json.indexOf('}'));
assertEquals(target.value, new BigDecimal(actual)); assertThat(new BigDecimal(actual)).isEqualTo(target.value);
} }
@Test @Test
@ -275,7 +273,7 @@ public class DefaultTypeAdaptersTest {
ClassWithBigDecimal expected = new ClassWithBigDecimal("-122.01e-21"); ClassWithBigDecimal expected = new ClassWithBigDecimal("-122.01e-21");
String json = expected.getExpectedJson(); String json = expected.getExpectedJson();
ClassWithBigDecimal actual = gson.fromJson(json, ClassWithBigDecimal.class); ClassWithBigDecimal actual = gson.fromJson(json, ClassWithBigDecimal.class);
assertEquals(expected.value, actual.value); assertThat(actual.value).isEqualTo(expected.value);
} }
@Test @Test
@ -290,7 +288,7 @@ public class DefaultTypeAdaptersTest {
public void testBigIntegerFieldSerialization() { public void testBigIntegerFieldSerialization() {
ClassWithBigInteger target = new ClassWithBigInteger("23232323215323234234324324324324324324"); ClassWithBigInteger target = new ClassWithBigInteger("23232323215323234234324324324324324324");
String json = gson.toJson(target); String json = gson.toJson(target);
assertEquals(target.getExpectedJson(), json); assertThat(json).isEqualTo(target.getExpectedJson());
} }
@Test @Test
@ -298,7 +296,7 @@ public class DefaultTypeAdaptersTest {
ClassWithBigInteger expected = new ClassWithBigInteger("879697697697697697697697697697697697"); ClassWithBigInteger expected = new ClassWithBigInteger("879697697697697697697697697697697697");
String json = expected.getExpectedJson(); String json = expected.getExpectedJson();
ClassWithBigInteger actual = gson.fromJson(json, ClassWithBigInteger.class); ClassWithBigInteger actual = gson.fromJson(json, ClassWithBigInteger.class);
assertEquals(expected.value, actual.value); assertThat(actual.value).isEqualTo(expected.value);
} }
@Test @Test
@ -306,8 +304,8 @@ public class DefaultTypeAdaptersTest {
gson = new GsonBuilder() gson = new GsonBuilder()
.registerTypeAdapter(BigInteger.class, new NumberAsStringAdapter(BigInteger.class)) .registerTypeAdapter(BigInteger.class, new NumberAsStringAdapter(BigInteger.class))
.create(); .create();
assertEquals("\"123\"", gson.toJson(new BigInteger("123"), BigInteger.class)); assertThat(gson.toJson(new BigInteger("123"), BigInteger.class)).isEqualTo("\"123\"");
assertEquals(new BigInteger("123"), gson.fromJson("\"123\"", BigInteger.class)); assertThat(gson.fromJson("\"123\"", BigInteger.class)).isEqualTo(new BigInteger("123"));
} }
@Test @Test
@ -315,35 +313,35 @@ public class DefaultTypeAdaptersTest {
gson = new GsonBuilder() gson = new GsonBuilder()
.registerTypeAdapter(BigDecimal.class, new NumberAsStringAdapter(BigDecimal.class)) .registerTypeAdapter(BigDecimal.class, new NumberAsStringAdapter(BigDecimal.class))
.create(); .create();
assertEquals("\"1.1\"", gson.toJson(new BigDecimal("1.1"), BigDecimal.class)); assertThat(gson.toJson(new BigDecimal("1.1"), BigDecimal.class)).isEqualTo("\"1.1\"");
assertEquals(new BigDecimal("1.1"), gson.fromJson("\"1.1\"", BigDecimal.class)); assertThat(gson.fromJson("\"1.1\"", BigDecimal.class)).isEqualTo(new BigDecimal("1.1"));
} }
@Test @Test
public void testSetSerialization() throws Exception { public void testSetSerialization() {
Gson gson = new Gson(); Gson gson = new Gson();
HashSet<String> s = new HashSet<>(); HashSet<String> s = new HashSet<>();
s.add("blah"); s.add("blah");
String json = gson.toJson(s); String json = gson.toJson(s);
assertEquals("[\"blah\"]", json); assertThat(json).isEqualTo("[\"blah\"]");
json = gson.toJson(s, Set.class); json = gson.toJson(s, Set.class);
assertEquals("[\"blah\"]", json); assertThat(json).isEqualTo("[\"blah\"]");
} }
@Test @Test
public void testBitSetSerialization() throws Exception { public void testBitSetSerialization() {
Gson gson = new Gson(); Gson gson = new Gson();
BitSet bits = new BitSet(); BitSet bits = new BitSet();
bits.set(1); bits.set(1);
bits.set(3, 6); bits.set(3, 6);
bits.set(9); bits.set(9);
String json = gson.toJson(bits); 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 @Test
public void testBitSetDeserialization() throws Exception { public void testBitSetDeserialization() {
BitSet expected = new BitSet(); BitSet expected = new BitSet();
expected.set(0); expected.set(0);
expected.set(2, 6); expected.set(2, 6);
@ -351,29 +349,29 @@ public class DefaultTypeAdaptersTest {
Gson gson = new Gson(); Gson gson = new Gson();
String json = gson.toJson(expected); 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]"; 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\"]"; 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]"; 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 { try {
gson.fromJson("[1, []]", BitSet.class); gson.fromJson("[1, []]", BitSet.class);
fail(); fail();
} catch (JsonSyntaxException e) { } 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 { try {
gson.fromJson("[1, 2]", BitSet.class); gson.fromJson("[1, 2]", BitSet.class);
fail(); fail();
} catch (JsonSyntaxException e) { } 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 class DefaultTypeAdaptersTest {
Date now = new Date(1315806903103L); Date now = new Date(1315806903103L);
String json = gson.toJson(now); String json = gson.toJson(now);
if (JavaVersion.isJava9OrLater()) { if (JavaVersion.isJava9OrLater()) {
assertEquals("\"Sep 11, 2011, 10:55:03 PM\"", json); assertThat(json).isEqualTo("\"Sep 11, 2011, 10:55:03 PM\"");
} else { } 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 class DefaultTypeAdaptersTest {
// millisecond portion. // millisecond portion.
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public static void assertEqualsDate(Date date, int year, int month, int day) { public static void assertEqualsDate(Date date, int year, int month, int day) {
assertEquals(year-1900, date.getYear()); assertThat(date.getYear()).isEqualTo(year-1900);
assertEquals(month, date.getMonth()); assertThat(date.getMonth()).isEqualTo(month);
assertEquals(day, date.getDate()); assertThat(date.getDate()).isEqualTo(day);
} }
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public static void assertEqualsTime(Date date, int hours, int minutes, int seconds) { public static void assertEqualsTime(Date date, int hours, int minutes, int seconds) {
assertEquals(hours, date.getHours()); assertThat(date.getHours()).isEqualTo(hours);
assertEquals(minutes, date.getMinutes()); assertThat(date.getMinutes()).isEqualTo(minutes);
assertEquals(seconds, date.getSeconds()); assertThat(date.getSeconds()).isEqualTo(seconds);
} }
@Test @Test
public void testDefaultDateSerializationUsingBuilder() throws Exception { public void testDefaultDateSerializationUsingBuilder() {
Gson gson = new GsonBuilder().create(); Gson gson = new GsonBuilder().create();
Date now = new Date(1315806903103L); Date now = new Date(1315806903103L);
String json = gson.toJson(now); String json = gson.toJson(now);
if (JavaVersion.isJava9OrLater()) { if (JavaVersion.isJava9OrLater()) {
assertEquals("\"Sep 11, 2011, 10:55:03 PM\"", json); assertThat(json).isEqualTo("\"Sep 11, 2011, 10:55:03 PM\"");
} else { } else {
assertEquals("\"Sep 11, 2011 10:55:03 PM\"", json); assertThat(json).isEqualTo("\"Sep 11, 2011 10:55:03 PM\"");
} }
} }
@Test @Test
public void testDefaultDateDeserializationUsingBuilder() throws Exception { public void testDefaultDateDeserializationUsingBuilder() {
Gson gson = new GsonBuilder().create(); Gson gson = new GsonBuilder().create();
Date now = new Date(1315806903103L); Date now = new Date(1315806903103L);
String json = gson.toJson(now); String json = gson.toJson(now);
Date extracted = gson.fromJson(json, Date.class); Date extracted = gson.fromJson(json, Date.class);
assertEquals(now.toString(), extracted.toString()); assertThat(extracted.toString()).isEqualTo(now.toString());
} }
@Test @Test
public void testDefaultCalendarSerialization() throws Exception { public void testDefaultCalendarSerialization() {
Gson gson = new GsonBuilder().create(); Gson gson = new GsonBuilder().create();
String json = gson.toJson(Calendar.getInstance()); String json = gson.toJson(Calendar.getInstance());
assertTrue(json.contains("year")); assertThat(json).contains("year");
assertTrue(json.contains("month")); assertThat(json).contains("month");
assertTrue(json.contains("dayOfMonth")); assertThat(json).contains("dayOfMonth");
assertTrue(json.contains("hourOfDay")); assertThat(json).contains("hourOfDay");
assertTrue(json.contains("minute")); assertThat(json).contains("minute");
assertTrue(json.contains("second")); assertThat(json).contains("second");
} }
@Test @Test
public void testDefaultCalendarDeserialization() throws Exception { public void testDefaultCalendarDeserialization() {
Gson gson = new GsonBuilder().create(); Gson gson = new GsonBuilder().create();
String json = "{year:2009,month:2,dayOfMonth:11,hourOfDay:14,minute:29,second:23}"; String json = "{year:2009,month:2,dayOfMonth:11,hourOfDay:14,minute:29,second:23}";
Calendar cal = gson.fromJson(json, Calendar.class); Calendar cal = gson.fromJson(json, Calendar.class);
assertEquals(2009, cal.get(Calendar.YEAR)); assertThat(cal.get(Calendar.YEAR)).isEqualTo(2009);
assertEquals(2, cal.get(Calendar.MONTH)); assertThat(cal.get(Calendar.MONTH)).isEqualTo(2);
assertEquals(11, cal.get(Calendar.DAY_OF_MONTH)); assertThat(cal.get(Calendar.DAY_OF_MONTH)).isEqualTo(11);
assertEquals(14, cal.get(Calendar.HOUR_OF_DAY)); assertThat(cal.get(Calendar.HOUR_OF_DAY)).isEqualTo(14);
assertEquals(29, cal.get(Calendar.MINUTE)); assertThat(cal.get(Calendar.MINUTE)).isEqualTo(29);
assertEquals(23, cal.get(Calendar.SECOND)); assertThat(cal.get(Calendar.SECOND)).isEqualTo(23);
} }
@Test @Test
public void testDefaultGregorianCalendarSerialization() throws Exception { public void testDefaultGregorianCalendarSerialization() {
Gson gson = new GsonBuilder().create(); Gson gson = new GsonBuilder().create();
GregorianCalendar cal = new GregorianCalendar(); GregorianCalendar cal = new GregorianCalendar();
String json = gson.toJson(cal); String json = gson.toJson(cal);
assertTrue(json.contains("year")); assertThat(json).contains("year");
assertTrue(json.contains("month")); assertThat(json).contains("month");
assertTrue(json.contains("dayOfMonth")); assertThat(json).contains("dayOfMonth");
assertTrue(json.contains("hourOfDay")); assertThat(json).contains("hourOfDay");
assertTrue(json.contains("minute")); assertThat(json).contains("minute");
assertTrue(json.contains("second")); assertThat(json).contains("second");
} }
@Test @Test
public void testDefaultGregorianCalendarDeserialization() throws Exception { public void testDefaultGregorianCalendarDeserialization() {
Gson gson = new GsonBuilder().create(); Gson gson = new GsonBuilder().create();
String json = "{year:2009,month:2,dayOfMonth:11,hourOfDay:14,minute:29,second:23}"; String json = "{year:2009,month:2,dayOfMonth:11,hourOfDay:14,minute:29,second:23}";
GregorianCalendar cal = gson.fromJson(json, GregorianCalendar.class); GregorianCalendar cal = gson.fromJson(json, GregorianCalendar.class);
assertEquals(2009, cal.get(Calendar.YEAR)); assertThat(cal.get(Calendar.YEAR)).isEqualTo(2009);
assertEquals(2, cal.get(Calendar.MONTH)); assertThat(cal.get(Calendar.MONTH)).isEqualTo(2);
assertEquals(11, cal.get(Calendar.DAY_OF_MONTH)); assertThat(cal.get(Calendar.DAY_OF_MONTH)).isEqualTo(11);
assertEquals(14, cal.get(Calendar.HOUR_OF_DAY)); assertThat(cal.get(Calendar.HOUR_OF_DAY)).isEqualTo(14);
assertEquals(29, cal.get(Calendar.MINUTE)); assertThat(cal.get(Calendar.MINUTE)).isEqualTo(29);
assertEquals(23, cal.get(Calendar.SECOND)); assertThat(cal.get(Calendar.SECOND)).isEqualTo(23);
} }
@Test @Test
public void testDateSerializationWithPattern() throws Exception { public void testDateSerializationWithPattern() {
String pattern = "yyyy-MM-dd"; String pattern = "yyyy-MM-dd";
Gson gson = new GsonBuilder().setDateFormat(DateFormat.FULL).setDateFormat(pattern).create(); Gson gson = new GsonBuilder().setDateFormat(DateFormat.FULL).setDateFormat(pattern).create();
Date now = new Date(1315806903103L); Date now = new Date(1315806903103L);
String json = gson.toJson(now); String json = gson.toJson(now);
assertEquals("\"2011-09-11\"", json); assertThat(json).isEqualTo("\"2011-09-11\"");
} }
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
@Test @Test
public void testDateDeserializationWithPattern() throws Exception { public void testDateDeserializationWithPattern() {
String pattern = "yyyy-MM-dd"; String pattern = "yyyy-MM-dd";
Gson gson = new GsonBuilder().setDateFormat(DateFormat.FULL).setDateFormat(pattern).create(); Gson gson = new GsonBuilder().setDateFormat(DateFormat.FULL).setDateFormat(pattern).create();
Date now = new Date(1315806903103L); Date now = new Date(1315806903103L);
String json = gson.toJson(now); String json = gson.toJson(now);
Date extracted = gson.fromJson(json, Date.class); Date extracted = gson.fromJson(json, Date.class);
assertEquals(now.getYear(), extracted.getYear()); assertThat(extracted.getYear()).isEqualTo(now.getYear());
assertEquals(now.getMonth(), extracted.getMonth()); assertThat(extracted.getMonth()).isEqualTo(now.getMonth());
assertEquals(now.getDay(), extracted.getDay()); assertThat(extracted.getDay()).isEqualTo(now.getDay());
} }
@Test @Test
public void testDateSerializationWithPatternNotOverridenByTypeAdapter() throws Exception { public void testDateSerializationWithPatternNotOverridenByTypeAdapter() {
String pattern = "yyyy-MM-dd"; String pattern = "yyyy-MM-dd";
Gson gson = new GsonBuilder() Gson gson = new GsonBuilder()
.setDateFormat(pattern) .setDateFormat(pattern)
@ -522,12 +520,12 @@ public class DefaultTypeAdaptersTest {
Date now = new Date(1315806903103L); Date now = new Date(1315806903103L);
String json = gson.toJson(now); 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 // http://code.google.com/p/google-gson/issues/detail?id=230
@Test @Test
public void testDateSerializationInCollection() throws Exception { public void testDateSerializationInCollection() {
Type listOfDates = new TypeToken<List<Date>>() {}.getType(); Type listOfDates = new TypeToken<List<Date>>() {}.getType();
TimeZone defaultTimeZone = TimeZone.getDefault(); TimeZone defaultTimeZone = TimeZone.getDefault();
TimeZone.setDefault(TimeZone.getTimeZone("UTC")); TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
@ -537,8 +535,8 @@ public class DefaultTypeAdaptersTest {
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create(); Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
List<Date> dates = Arrays.asList(new Date(0)); List<Date> dates = Arrays.asList(new Date(0));
String json = gson.toJson(dates, listOfDates); String json = gson.toJson(dates, listOfDates);
assertEquals("[\"1970-01-01\"]", json); assertThat(json).isEqualTo("[\"1970-01-01\"]");
assertEquals(0L, gson.<List<Date>>fromJson("[\"1970-01-01\"]", listOfDates).get(0).getTime()); assertThat(gson.<List<Date>>fromJson("[\"1970-01-01\"]", listOfDates).get(0).getTime()).isEqualTo(0L);
} finally { } finally {
TimeZone.setDefault(defaultTimeZone); TimeZone.setDefault(defaultTimeZone);
Locale.setDefault(defaultLocale); Locale.setDefault(defaultLocale);
@ -547,34 +545,34 @@ public class DefaultTypeAdaptersTest {
@Test @Test
public void testJsonPrimitiveSerialization() { public void testJsonPrimitiveSerialization() {
assertEquals("5", gson.toJson(new JsonPrimitive(5), JsonElement.class)); assertThat(gson.toJson(new JsonPrimitive(5), JsonElement.class)).isEqualTo("5");
assertEquals("true", gson.toJson(new JsonPrimitive(true), JsonElement.class)); assertThat(gson.toJson(new JsonPrimitive(true), JsonElement.class)).isEqualTo("true");
assertEquals("\"foo\"", gson.toJson(new JsonPrimitive("foo"), JsonElement.class)); assertThat(gson.toJson(new JsonPrimitive("foo"), JsonElement.class)).isEqualTo("\"foo\"");
assertEquals("\"a\"", gson.toJson(new JsonPrimitive('a'), JsonElement.class)); assertThat(gson.toJson(new JsonPrimitive('a'), JsonElement.class)).isEqualTo("\"a\"");
} }
@Test @Test
public void testJsonPrimitiveDeserialization() { public void testJsonPrimitiveDeserialization() {
assertEquals(new JsonPrimitive(5), gson.fromJson("5", JsonElement.class)); assertThat(gson.fromJson("5", JsonElement.class)).isEqualTo(new JsonPrimitive(5));
assertEquals(new JsonPrimitive(5), gson.fromJson("5", JsonPrimitive.class)); assertThat(gson.fromJson("5", JsonPrimitive.class)).isEqualTo(new JsonPrimitive(5));
assertEquals(new JsonPrimitive(true), gson.fromJson("true", JsonElement.class)); assertThat(gson.fromJson("true", JsonElement.class)).isEqualTo(new JsonPrimitive(true));
assertEquals(new JsonPrimitive(true), gson.fromJson("true", JsonPrimitive.class)); assertThat(gson.fromJson("true", JsonPrimitive.class)).isEqualTo(new JsonPrimitive(true));
assertEquals(new JsonPrimitive("foo"), gson.fromJson("\"foo\"", JsonElement.class)); assertThat(gson.fromJson("\"foo\"", JsonElement.class)).isEqualTo(new JsonPrimitive("foo"));
assertEquals(new JsonPrimitive("foo"), gson.fromJson("\"foo\"", JsonPrimitive.class)); assertThat(gson.fromJson("\"foo\"", JsonPrimitive.class)).isEqualTo(new JsonPrimitive("foo"));
assertEquals(new JsonPrimitive('a'), gson.fromJson("\"a\"", JsonElement.class)); assertThat(gson.fromJson("\"a\"", JsonElement.class)).isEqualTo(new JsonPrimitive('a'));
assertEquals(new JsonPrimitive('a'), gson.fromJson("\"a\"", JsonPrimitive.class)); assertThat(gson.fromJson("\"a\"", JsonPrimitive.class)).isEqualTo(new JsonPrimitive('a'));
} }
@Test @Test
public void testJsonNullSerialization() { public void testJsonNullSerialization() {
assertEquals("null", gson.toJson(JsonNull.INSTANCE, JsonElement.class)); assertThat(gson.toJson(JsonNull.INSTANCE, JsonElement.class)).isEqualTo("null");
assertEquals("null", gson.toJson(JsonNull.INSTANCE, JsonNull.class)); assertThat(gson.toJson(JsonNull.INSTANCE, JsonNull.class)).isEqualTo("null");
} }
@Test @Test
public void testNullJsonElementSerialization() { public void testNullJsonElementSerialization() {
assertEquals("null", gson.toJson(null, JsonElement.class)); assertThat(gson.toJson(null, JsonElement.class)).isEqualTo("null");
assertEquals("null", gson.toJson(null, JsonNull.class)); assertThat(gson.toJson(null, JsonNull.class)).isEqualTo("null");
} }
@Test @Test
@ -583,7 +581,7 @@ public class DefaultTypeAdaptersTest {
array.add(new JsonPrimitive(1)); array.add(new JsonPrimitive(1));
array.add(new JsonPrimitive(2)); array.add(new JsonPrimitive(2));
array.add(new JsonPrimitive(3)); 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 @Test
@ -594,8 +592,8 @@ public class DefaultTypeAdaptersTest {
array.add(new JsonPrimitive(3)); array.add(new JsonPrimitive(3));
String json = "[1,2,3]"; String json = "[1,2,3]";
assertEquals(array, gson.fromJson(json, JsonElement.class)); assertThat(gson.fromJson(json, JsonElement.class)).isEqualTo(array);
assertEquals(array, gson.fromJson(json, JsonArray.class)); assertThat(gson.fromJson(json, JsonArray.class)).isEqualTo(array);
} }
@Test @Test
@ -603,7 +601,7 @@ public class DefaultTypeAdaptersTest {
JsonObject object = new JsonObject(); JsonObject object = new JsonObject();
object.add("foo", new JsonPrimitive(1)); object.add("foo", new JsonPrimitive(1));
object.add("bar", new JsonPrimitive(2)); 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 @Test
@ -614,16 +612,16 @@ public class DefaultTypeAdaptersTest {
String json = "{\"foo\":1,\"bar\":2}"; String json = "{\"foo\":1,\"bar\":2}";
JsonElement actual = gson.fromJson(json, JsonElement.class); JsonElement actual = gson.fromJson(json, JsonElement.class);
assertEquals(object, actual); assertThat(actual).isEqualTo(object);
JsonObject actualObj = gson.fromJson(json, JsonObject.class); JsonObject actualObj = gson.fromJson(json, JsonObject.class);
assertEquals(object, actualObj); assertThat(actualObj).isEqualTo(object);
} }
@Test @Test
public void testJsonNullDeserialization() { public void testJsonNullDeserialization() {
assertEquals(JsonNull.INSTANCE, gson.fromJson("null", JsonElement.class)); assertThat(gson.fromJson("null", JsonElement.class)).isEqualTo(JsonNull.INSTANCE);
assertEquals(JsonNull.INSTANCE, gson.fromJson("null", JsonNull.class)); assertThat(gson.fromJson("null", JsonNull.class)).isEqualTo(JsonNull.INSTANCE);
} }
@Test @Test
@ -632,8 +630,7 @@ public class DefaultTypeAdaptersTest {
gson.fromJson("\"abc\"", JsonObject.class); gson.fromJson("\"abc\"", JsonObject.class);
fail(); fail();
} catch (JsonSyntaxException expected) { } catch (JsonSyntaxException expected) {
assertEquals("Expected a com.google.gson.JsonObject but was com.google.gson.JsonPrimitive; at path $", assertThat(expected.getMessage()).isEqualTo("Expected a com.google.gson.JsonObject but was com.google.gson.JsonPrimitive; at path $");
expected.getMessage());
} }
} }
@ -663,14 +660,14 @@ public class DefaultTypeAdaptersTest {
props.setProperty("foo", "bar"); props.setProperty("foo", "bar");
String json = gson.toJson(props); String json = gson.toJson(props);
String expected = "{\"foo\":\"bar\"}"; String expected = "{\"foo\":\"bar\"}";
assertEquals(expected, json); assertThat(json).isEqualTo(expected);
} }
@Test @Test
public void testPropertiesDeserialization() { public void testPropertiesDeserialization() {
String json = "{foo:'bar'}"; String json = "{foo:'bar'}";
Properties props = gson.fromJson(json, Properties.class); Properties props = gson.fromJson(json, Properties.class);
assertEquals("bar", props.getProperty("foo")); assertThat(props.getProperty("foo")).isEqualTo("bar");
} }
@Test @Test
@ -678,7 +675,7 @@ public class DefaultTypeAdaptersTest {
TreeSet<String> treeSet = new TreeSet<>(); TreeSet<String> treeSet = new TreeSet<>();
treeSet.add("Value1"); treeSet.add("Value1");
String json = gson.toJson(treeSet); String json = gson.toJson(treeSet);
assertEquals("[\"Value1\"]", json); assertThat(json).isEqualTo("[\"Value1\"]");
} }
@Test @Test
@ -686,33 +683,33 @@ public class DefaultTypeAdaptersTest {
String json = "['Value1']"; String json = "['Value1']";
Type type = new TypeToken<TreeSet<String>>() {}.getType(); Type type = new TypeToken<TreeSet<String>>() {}.getType();
TreeSet<String> treeSet = gson.fromJson(json, type); TreeSet<String> treeSet = gson.fromJson(json, type);
assertTrue(treeSet.contains("Value1")); assertThat(treeSet).contains("Value1");
} }
@Test @Test
public void testStringBuilderSerialization() { public void testStringBuilderSerialization() {
StringBuilder sb = new StringBuilder("abc"); StringBuilder sb = new StringBuilder("abc");
String json = gson.toJson(sb); String json = gson.toJson(sb);
assertEquals("\"abc\"", json); assertThat(json).isEqualTo("\"abc\"");
} }
@Test @Test
public void testStringBuilderDeserialization() { public void testStringBuilderDeserialization() {
StringBuilder sb = gson.fromJson("'abc'", StringBuilder.class); StringBuilder sb = gson.fromJson("'abc'", StringBuilder.class);
assertEquals("abc", sb.toString()); assertThat(sb.toString()).isEqualTo("abc");
} }
@Test @Test
public void testStringBufferSerialization() { public void testStringBufferSerialization() {
StringBuffer sb = new StringBuffer("abc"); StringBuffer sb = new StringBuffer("abc");
String json = gson.toJson(sb); String json = gson.toJson(sb);
assertEquals("\"abc\"", json); assertThat(json).isEqualTo("\"abc\"");
} }
@Test @Test
public void testStringBufferDeserialization() { public void testStringBufferDeserialization() {
StringBuffer sb = gson.fromJson("'abc'", StringBuffer.class); StringBuffer sb = gson.fromJson("'abc'", StringBuffer.class);
assertEquals("abc", sb.toString()); assertThat(sb.toString()).isEqualTo("abc");
} }
private static class MyClassTypeAdapter extends TypeAdapter<Class<?>> { private static class MyClassTypeAdapter extends TypeAdapter<Class<?>> {

View File

@ -15,7 +15,7 @@
*/ */
package com.google.gson.functional; 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.Gson;
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;
@ -58,8 +58,8 @@ public class DelegateTypeAdapterTest {
String json = gson.toJson(bags); String json = gson.toJson(bags);
bags = gson.fromJson(json, new TypeToken<List<BagOfPrimitives>>(){}.getType()); bags = gson.fromJson(json, new TypeToken<List<BagOfPrimitives>>(){}.getType());
// 11: 1 list object, and 10 entries. stats invoked on all 5 fields // 11: 1 list object, and 10 entries. stats invoked on all 5 fields
assertEquals(51, stats.numReads); assertThat(stats.numReads).isEqualTo(51);
assertEquals(51, stats.numWrites); assertThat(stats.numWrites).isEqualTo(51);
} }
@Test @Test
@ -68,8 +68,8 @@ public class DelegateTypeAdapterTest {
String json = gson.toJson(bags); String json = gson.toJson(bags);
bags = gson.fromJson(json, String[].class); bags = gson.fromJson(json, String[].class);
// 1 array object with 4 elements. // 1 array object with 4 elements.
assertEquals(5, stats.numReads); assertThat(stats.numReads).isEqualTo(5);
assertEquals(5, stats.numWrites); assertThat(stats.numWrites).isEqualTo(5);
} }
private static class StatsTypeAdapterFactory implements TypeAdapterFactory { private static class StatsTypeAdapterFactory implements TypeAdapterFactory {

View File

@ -16,10 +16,7 @@
package com.google.gson.functional; package com.google.gson.functional;
import static org.junit.Assert.assertEquals; import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;
@ -60,15 +57,15 @@ public class EnumTest {
} }
@Test @Test
public void testTopLevelEnumSerialization() throws Exception { public void testTopLevelEnumSerialization() {
String result = gson.toJson(MyEnum.VALUE1); String result = gson.toJson(MyEnum.VALUE1);
assertEquals('"' + MyEnum.VALUE1.toString() + '"', result); assertThat(result).isEqualTo('"' + MyEnum.VALUE1.toString() + '"');
} }
@Test @Test
public void testTopLevelEnumDeserialization() throws Exception { public void testTopLevelEnumDeserialization() {
MyEnum result = gson.fromJson('"' + MyEnum.VALUE1.toString() + '"', MyEnum.class); MyEnum result = gson.fromJson('"' + MyEnum.VALUE1.toString() + '"', MyEnum.class);
assertEquals(MyEnum.VALUE1, result); assertThat(result).isEqualTo(MyEnum.VALUE1);
} }
@Test @Test
@ -79,9 +76,9 @@ public class EnumTest {
target.add(MyEnum.VALUE2); target.add(MyEnum.VALUE2);
String expectedJson = "[\"VALUE1\",\"VALUE2\"]"; String expectedJson = "[\"VALUE1\",\"VALUE2\"]";
String actualJson = gson.toJson(target); String actualJson = gson.toJson(target);
assertEquals(expectedJson, actualJson); assertThat(actualJson).isEqualTo(expectedJson);
actualJson = gson.toJson(target, type); actualJson = gson.toJson(target, type);
assertEquals(expectedJson, actualJson); assertThat(actualJson).isEqualTo(expectedJson);
} }
@Test @Test
@ -94,17 +91,17 @@ public class EnumTest {
} }
@Test @Test
public void testClassWithEnumFieldSerialization() throws Exception { public void testClassWithEnumFieldSerialization() {
ClassWithEnumFields target = new ClassWithEnumFields(); ClassWithEnumFields target = new ClassWithEnumFields();
assertEquals(target.getExpectedJson(), gson.toJson(target)); assertThat(gson.toJson(target)).isEqualTo(target.getExpectedJson());
} }
@Test @Test
public void testClassWithEnumFieldDeserialization() throws Exception { public void testClassWithEnumFieldDeserialization() {
String json = "{value1:'VALUE1',value2:'VALUE2'}"; String json = "{value1:'VALUE1',value2:'VALUE2'}";
ClassWithEnumFields target = gson.fromJson(json, ClassWithEnumFields.class); ClassWithEnumFields target = gson.fromJson(json, ClassWithEnumFields.class);
assertEquals(MyEnum.VALUE1,target.value1); assertThat(target.value1).isEqualTo(MyEnum.VALUE1);
assertEquals(MyEnum.VALUE2,target.value2); assertThat(target.value2).isEqualTo(MyEnum.VALUE2);
} }
private static enum MyEnum { private static enum MyEnum {
@ -124,12 +121,13 @@ public class EnumTest {
*/ */
@Test @Test
public void testEnumSubclass() { public void testEnumSubclass() {
assertFalse(Roshambo.class == Roshambo.ROCK.getClass()); assertThat(Roshambo.ROCK.getClass()).isAssignableTo(Roshambo.class);
assertEquals("\"ROCK\"", gson.toJson(Roshambo.ROCK)); assertThat(gson.toJson(Roshambo.ROCK)).isEqualTo("\"ROCK\"");
assertEquals("[\"ROCK\",\"PAPER\",\"SCISSORS\"]", gson.toJson(EnumSet.allOf(Roshambo.class))); assertThat(gson.toJson(EnumSet.allOf(Roshambo.class))).isEqualTo("[\"ROCK\",\"PAPER\",\"SCISSORS\"]");
assertEquals(Roshambo.ROCK, gson.fromJson("\"ROCK\"", Roshambo.class)); assertThat(gson.fromJson("\"ROCK\"", Roshambo.class)).isEqualTo(Roshambo.ROCK);
assertEquals(EnumSet.allOf(Roshambo.class), assertThat(EnumSet.allOf(Roshambo.class)).isEqualTo(
gson.fromJson("[\"ROCK\",\"PAPER\",\"SCISSORS\"]", new TypeToken<Set<Roshambo>>() {}.getType())); gson.fromJson("[\"ROCK\",\"PAPER\",\"SCISSORS\"]", new TypeToken<Set<Roshambo>>() {}.getType())
);
} }
@Test @Test
@ -137,12 +135,13 @@ public class EnumTest {
gson = new GsonBuilder() gson = new GsonBuilder()
.registerTypeHierarchyAdapter(Roshambo.class, new MyEnumTypeAdapter()) .registerTypeHierarchyAdapter(Roshambo.class, new MyEnumTypeAdapter())
.create(); .create();
assertFalse(Roshambo.class == Roshambo.ROCK.getClass()); assertThat(Roshambo.ROCK.getClass()).isAssignableTo(Roshambo.class);
assertEquals("\"123ROCK\"", gson.toJson(Roshambo.ROCK)); assertThat(gson.toJson(Roshambo.ROCK)).isEqualTo("\"123ROCK\"");
assertEquals("[\"123ROCK\",\"123PAPER\",\"123SCISSORS\"]", gson.toJson(EnumSet.allOf(Roshambo.class))); assertThat(gson.toJson(EnumSet.allOf(Roshambo.class))).isEqualTo("[\"123ROCK\",\"123PAPER\",\"123SCISSORS\"]");
assertEquals(Roshambo.ROCK, gson.fromJson("\"123ROCK\"", Roshambo.class)); assertThat(gson.fromJson("\"123ROCK\"", Roshambo.class)).isEqualTo(Roshambo.ROCK);
assertEquals(EnumSet.allOf(Roshambo.class), assertThat(EnumSet.allOf(Roshambo.class)).isEqualTo(
gson.fromJson("[\"123ROCK\",\"123PAPER\",\"123SCISSORS\"]", new TypeToken<Set<Roshambo>>() {}.getType())); gson.fromJson("[\"123ROCK\",\"123PAPER\",\"123SCISSORS\"]", new TypeToken<Set<Roshambo>>() {}.getType())
);
} }
@Test @Test
@ -152,7 +151,7 @@ public class EnumTest {
list.add(Roshambo.PAPER); list.add(Roshambo.PAPER);
String json = gson.toJson(list); String json = gson.toJson(list);
assertEquals("[\"ROCK\",\"PAPER\"]", json); assertThat(json).isEqualTo("[\"ROCK\",\"PAPER\"]");
Type collectionType = new TypeToken<Collection<Roshambo>>() {}.getType(); Type collectionType = new TypeToken<Collection<Roshambo>>() {}.getType();
Collection<Roshambo> actualJsonList = gson.fromJson(json, collectionType); Collection<Roshambo> actualJsonList = gson.fromJson(json, collectionType);
@ -162,34 +161,33 @@ public class EnumTest {
@Test @Test
public void testEnumCaseMapping() { public void testEnumCaseMapping() {
assertEquals(Gender.MALE, gson.fromJson("\"boy\"", Gender.class)); assertThat(gson.fromJson("\"boy\"", Gender.class)).isEqualTo(Gender.MALE);
assertEquals("\"boy\"", gson.toJson(Gender.MALE, Gender.class)); assertThat(gson.toJson(Gender.MALE, Gender.class)).isEqualTo("\"boy\"");
} }
@Test @Test
public void testEnumSet() { public void testEnumSet() {
EnumSet<Roshambo> foo = EnumSet.of(Roshambo.ROCK, Roshambo.PAPER); EnumSet<Roshambo> foo = EnumSet.of(Roshambo.ROCK, Roshambo.PAPER);
String json = gson.toJson(foo); String json = gson.toJson(foo);
assertEquals("[\"ROCK\",\"PAPER\"]", json); assertThat(json).isEqualTo("[\"ROCK\",\"PAPER\"]");
Type type = new TypeToken<EnumSet<Roshambo>>() {}.getType(); Type type = new TypeToken<EnumSet<Roshambo>>() {}.getType();
EnumSet<Roshambo> bar = gson.fromJson(json, type); EnumSet<Roshambo> bar = gson.fromJson(json, type);
assertTrue(bar.contains(Roshambo.ROCK)); assertThat(bar).containsExactly(Roshambo.ROCK, Roshambo.PAPER).inOrder();
assertTrue(bar.contains(Roshambo.PAPER)); assertThat(bar).doesNotContain(Roshambo.SCISSORS);;
assertFalse(bar.contains(Roshambo.SCISSORS));
} }
@Test @Test
public void testEnumMap() throws Exception { public void testEnumMap() {
EnumMap<MyEnum, String> map = new EnumMap<>(MyEnum.class); EnumMap<MyEnum, String> map = new EnumMap<>(MyEnum.class);
map.put(MyEnum.VALUE1, "test"); map.put(MyEnum.VALUE1, "test");
String json = gson.toJson(map); String json = gson.toJson(map);
assertEquals("{\"VALUE1\":\"test\"}", json); assertThat(json).isEqualTo("{\"VALUE1\":\"test\"}");
Type type = new TypeToken<EnumMap<MyEnum, String>>() {}.getType(); Type type = new TypeToken<EnumMap<MyEnum, String>>() {}.getType();
EnumMap<?, ?> actualMap = gson.fromJson("{\"VALUE1\":\"test\"}", type); EnumMap<?, ?> actualMap = gson.fromJson("{\"VALUE1\":\"test\"}", type);
Map<?, ?> expectedMap = Collections.singletonMap(MyEnum.VALUE1, "test"); Map<?, ?> expectedMap = Collections.singletonMap(MyEnum.VALUE1, "test");
assertEquals(expectedMap, actualMap); assertThat(actualMap).isEqualTo(expectedMap);
} }
private enum Roshambo { private enum Roshambo {
@ -234,9 +232,9 @@ public class EnumTest {
@Test @Test
public void testEnumClassWithFields() { public void testEnumClassWithFields() {
assertEquals("\"RED\"", gson.toJson(Color.RED)); assertThat(gson.toJson(Color.RED)).isEqualTo("\"RED\"");
assertEquals("red", gson.fromJson("RED", Color.class).value); assertThat(gson.fromJson("RED", Color.class).value).isEqualTo("red");
assertEquals(2, gson.fromJson("BLUE", Color.class).index); assertThat(gson.fromJson("BLUE", Color.class).index).isEqualTo(2);
} }
private enum Color { private enum Color {
@ -252,11 +250,11 @@ public class EnumTest {
@Test @Test
public void testEnumToStringRead() { public void testEnumToStringRead() {
// Should still be able to read constant name // 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 // 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 { private enum CustomToString {
@ -274,8 +272,8 @@ public class EnumTest {
*/ */
@Test @Test
public void testEnumToStringReadInterchanged() { public void testEnumToStringReadInterchanged() {
assertEquals(InterchangedToString.A, gson.fromJson("\"A\"", InterchangedToString.class)); assertThat(gson.fromJson("\"A\"", InterchangedToString.class)).isEqualTo(InterchangedToString.A);
assertEquals(InterchangedToString.B, gson.fromJson("\"B\"", InterchangedToString.class)); assertThat(gson.fromJson("\"B\"", InterchangedToString.class)).isEqualTo(InterchangedToString.B);
} }
private enum InterchangedToString { private enum InterchangedToString {

View File

@ -16,7 +16,7 @@
package com.google.gson.functional; 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.Assert.fail;
import com.google.gson.Gson; import com.google.gson.Gson;
@ -55,7 +55,7 @@ public class EnumWithObfuscatedTest {
} }
} }
assertEquals(Gender.MALE, gson.fromJson("\"MAIL\"", Gender.class)); assertThat(gson.fromJson("\"MAIL\"", Gender.class)).isEqualTo(Gender.MALE);
assertEquals("\"MAIL\"", gson.toJson(Gender.MALE, Gender.class)); assertThat(gson.toJson(Gender.MALE, Gender.class)).isEqualTo("\"MAIL\"");
} }
} }

View File

@ -16,9 +16,7 @@
package com.google.gson.functional; package com.google.gson.functional;
import static org.junit.Assert.assertEquals; import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;
@ -43,12 +41,12 @@ public class EscapingTest {
} }
@Test @Test
public void testEscapingQuotesInStringArray() throws Exception { public void testEscapingQuotesInStringArray() {
String[] valueWithQuotes = { "beforeQuote\"afterQuote" }; String[] valueWithQuotes = { "beforeQuote\"afterQuote" };
String jsonRepresentation = gson.toJson(valueWithQuotes); String jsonRepresentation = gson.toJson(valueWithQuotes);
String[] target = gson.fromJson(jsonRepresentation, String[].class); String[] target = gson.fromJson(jsonRepresentation, String[].class);
assertEquals(1, target.length); assertThat(target.length).isEqualTo(1);
assertEquals(valueWithQuotes[0], target[0]); assertThat(target[0]).isEqualTo(valueWithQuotes[0]);
} }
@Test @Test
@ -60,34 +58,33 @@ public class EscapingTest {
strings.add("&"); strings.add("&");
strings.add("'"); strings.add("'");
strings.add("\""); strings.add("\"");
assertEquals("[\"\\u003c\",\"\\u003e\",\"\\u003d\",\"\\u0026\",\"\\u0027\",\"\\\"\"]", assertThat(gson.toJson(strings)).isEqualTo("[\"\\u003c\",\"\\u003e\",\"\\u003d\",\"\\u0026\",\"\\u0027\",\"\\\"\"]");
gson.toJson(strings));
} }
@Test @Test
public void testEscapingObjectFields() throws Exception { public void testEscapingObjectFields() {
BagOfPrimitives objWithPrimitives = new BagOfPrimitives(1L, 1, true, "test with\" <script>"); BagOfPrimitives objWithPrimitives = new BagOfPrimitives(1L, 1, true, "test with\" <script>");
String jsonRepresentation = gson.toJson(objWithPrimitives); String jsonRepresentation = gson.toJson(objWithPrimitives);
assertFalse(jsonRepresentation.contains("<")); assertThat(jsonRepresentation).doesNotContain("<");
assertFalse(jsonRepresentation.contains(">")); assertThat(jsonRepresentation).doesNotContain(">");
assertTrue(jsonRepresentation.contains("\\\"")); assertThat(jsonRepresentation).contains("\\\"");
BagOfPrimitives expectedObject = gson.fromJson(jsonRepresentation, BagOfPrimitives.class); BagOfPrimitives expectedObject = gson.fromJson(jsonRepresentation, BagOfPrimitives.class);
assertEquals(objWithPrimitives.getExpectedJson(), expectedObject.getExpectedJson()); assertThat(expectedObject.getExpectedJson()).isEqualTo(objWithPrimitives.getExpectedJson());
} }
@Test @Test
public void testGsonAcceptsEscapedAndNonEscapedJsonDeserialization() throws Exception { public void testGsonAcceptsEscapedAndNonEscapedJsonDeserialization() {
Gson escapeHtmlGson = new GsonBuilder().create(); Gson escapeHtmlGson = new GsonBuilder().create();
Gson noEscapeHtmlGson = new GsonBuilder().disableHtmlEscaping().create(); Gson noEscapeHtmlGson = new GsonBuilder().disableHtmlEscaping().create();
BagOfPrimitives target = new BagOfPrimitives(1L, 1, true, "test' / w'ith\" / \\ <script>"); BagOfPrimitives target = new BagOfPrimitives(1L, 1, true, "test' / w'ith\" / \\ <script>");
String escapedJsonForm = escapeHtmlGson.toJson(target); String escapedJsonForm = escapeHtmlGson.toJson(target);
String nonEscapedJsonForm = noEscapeHtmlGson.toJson(target); String nonEscapedJsonForm = noEscapeHtmlGson.toJson(target);
assertFalse(escapedJsonForm.equals(nonEscapedJsonForm)); assertThat(escapedJsonForm.equals(nonEscapedJsonForm)).isFalse();
assertEquals(target, noEscapeHtmlGson.fromJson(escapedJsonForm, BagOfPrimitives.class)); assertThat(noEscapeHtmlGson.fromJson(escapedJsonForm, BagOfPrimitives.class)).isEqualTo(target);
assertEquals(target, escapeHtmlGson.fromJson(nonEscapedJsonForm, BagOfPrimitives.class)); assertThat(escapeHtmlGson.fromJson(nonEscapedJsonForm, BagOfPrimitives.class)).isEqualTo(target);
} }
@Test @Test
@ -96,6 +93,6 @@ public class EscapingTest {
String json = gson.toJson(gson.toJson(expected)); String json = gson.toJson(gson.toJson(expected));
String value = gson.fromJson(json, String.class); String value = gson.fromJson(json, String.class);
BagOfPrimitives actual = gson.fromJson(value, BagOfPrimitives.class); BagOfPrimitives actual = gson.fromJson(value, BagOfPrimitives.class);
assertEquals(expected, actual); assertThat(actual).isEqualTo(expected);
} }
} }

View File

@ -16,10 +16,7 @@
package com.google.gson.functional; package com.google.gson.functional;
import static org.junit.Assert.assertEquals; import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import com.google.gson.ExclusionStrategy; import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes; import com.google.gson.FieldAttributes;
@ -59,12 +56,12 @@ public class ExclusionStrategyFunctionalTest {
} }
@Test @Test
public void testExclusionStrategySerialization() throws Exception { public void testExclusionStrategySerialization() {
Gson gson = createGson(new MyExclusionStrategy(String.class), true); Gson gson = createGson(new MyExclusionStrategy(String.class), true);
String json = gson.toJson(src); String json = gson.toJson(src);
assertFalse(json.contains("\"stringField\"")); assertThat(json).doesNotContain("\"stringField\"");
assertFalse(json.contains("\"annotatedField\"")); assertThat(json).doesNotContain("\"annotatedField\"");
assertTrue(json.contains("\"longField\"")); assertThat(json).contains("\"longField\"");
} }
@Test @Test
@ -72,13 +69,13 @@ public class ExclusionStrategyFunctionalTest {
String json = "{\"annotatedField\":1,\"stringField\":\"x\",\"longField\":2}"; String json = "{\"annotatedField\":1,\"stringField\":\"x\",\"longField\":2}";
Gson gson = createGson(new MyExclusionStrategy(String.class), true); Gson gson = createGson(new MyExclusionStrategy(String.class), true);
SampleObjectForTest value = gson.fromJson(json, SampleObjectForTest.class); SampleObjectForTest value = gson.fromJson(json, SampleObjectForTest.class);
assertEquals(1, value.annotatedField); assertThat(value.annotatedField).isEqualTo(1);
assertEquals("x", value.stringField); assertThat(value.stringField).isEqualTo("x");
assertEquals(2, value.longField); assertThat(value.longField).isEqualTo(2);
} }
@Test @Test
public void testExclusionStrategyDeserialization() throws Exception { public void testExclusionStrategyDeserialization() {
Gson gson = createGson(new MyExclusionStrategy(String.class), false); Gson gson = createGson(new MyExclusionStrategy(String.class), false);
JsonObject json = new JsonObject(); JsonObject json = new JsonObject();
json.add("annotatedField", new JsonPrimitive(src.annotatedField + 5)); json.add("annotatedField", new JsonPrimitive(src.annotatedField + 5));
@ -86,40 +83,40 @@ public class ExclusionStrategyFunctionalTest {
json.add("longField", new JsonPrimitive(1212311L)); json.add("longField", new JsonPrimitive(1212311L));
SampleObjectForTest target = gson.fromJson(json, SampleObjectForTest.class); SampleObjectForTest target = gson.fromJson(json, SampleObjectForTest.class);
assertEquals(1212311L, target.longField); assertThat(target.longField).isEqualTo(1212311L);
// assert excluded fields are set to the defaults // assert excluded fields are set to the defaults
assertEquals(src.annotatedField, target.annotatedField); assertThat(target.annotatedField).isEqualTo(src.annotatedField);
assertEquals(src.stringField, target.stringField); assertThat(target.stringField).isEqualTo(src.stringField);
} }
@Test @Test
public void testExclusionStrategySerializationDoesNotImpactSerialization() throws Exception { public void testExclusionStrategySerializationDoesNotImpactSerialization() {
Gson gson = createGson(new MyExclusionStrategy(String.class), false); Gson gson = createGson(new MyExclusionStrategy(String.class), false);
String json = gson.toJson(src); String json = gson.toJson(src);
assertTrue(json.contains("\"stringField\"")); assertThat(json).contains("\"stringField\"");
assertTrue(json.contains("\"annotatedField\"")); assertThat(json).contains("\"annotatedField\"");
assertTrue(json.contains("\"longField\"")); assertThat(json).contains("\"longField\"");
} }
@Test @Test
public void testExclusionStrategyWithMode() throws Exception { public void testExclusionStrategyWithMode() {
SampleObjectForTest testObj = new SampleObjectForTest( SampleObjectForTest testObj = new SampleObjectForTest(
src.annotatedField + 5, src.stringField + "blah,blah", src.annotatedField + 5, src.stringField + "blah,blah",
src.longField + 655L); src.longField + 655L);
Gson gson = createGson(new MyExclusionStrategy(String.class), false); Gson gson = createGson(new MyExclusionStrategy(String.class), false);
JsonObject json = gson.toJsonTree(testObj).getAsJsonObject(); JsonObject json = gson.toJsonTree(testObj).getAsJsonObject();
assertEquals(testObj.annotatedField, json.get("annotatedField").getAsInt()); assertThat(json.get("annotatedField").getAsInt()).isEqualTo(testObj.annotatedField);
assertEquals(testObj.stringField, json.get("stringField").getAsString()); assertThat(json.get("stringField").getAsString()).isEqualTo(testObj.stringField);
assertEquals(testObj.longField, json.get("longField").getAsLong()); assertThat(json.get("longField").getAsLong()).isEqualTo(testObj.longField);
SampleObjectForTest target = gson.fromJson(json, SampleObjectForTest.class); SampleObjectForTest target = gson.fromJson(json, SampleObjectForTest.class);
assertEquals(testObj.longField, target.longField); assertThat(target.longField).isEqualTo(testObj.longField);
// assert excluded fields are set to the defaults // assert excluded fields are set to the defaults
assertEquals(src.annotatedField, target.annotatedField); assertThat(target.annotatedField).isEqualTo(src.annotatedField);
assertEquals(src.stringField, target.stringField); assertThat(target.stringField).isEqualTo(src.stringField);
} }
@Test @Test
@ -127,7 +124,7 @@ public class ExclusionStrategyFunctionalTest {
Gson gson = new GsonBuilder() Gson gson = new GsonBuilder()
.addSerializationExclusionStrategy(EXCLUDE_SAMPLE_OBJECT_FOR_TEST) .addSerializationExclusionStrategy(EXCLUDE_SAMPLE_OBJECT_FOR_TEST)
.create(); .create();
assertEquals("null", gson.toJson(new SampleObjectForTest(), SampleObjectForTest.class)); assertThat(gson.toJson(new SampleObjectForTest(), SampleObjectForTest.class)).isEqualTo("null");
} }
@Test @Test
@ -137,9 +134,9 @@ public class ExclusionStrategyFunctionalTest {
.create(); .create();
String json = "{\"annotatedField\":1,\"stringField\":\"x\",\"longField\":2}"; String json = "{\"annotatedField\":1,\"stringField\":\"x\",\"longField\":2}";
SampleObjectForTest value = gson.fromJson(json, SampleObjectForTest.class); SampleObjectForTest value = gson.fromJson(json, SampleObjectForTest.class);
assertEquals(1, value.annotatedField); assertThat(value.annotatedField).isEqualTo(1);
assertEquals("x", value.stringField); assertThat(value.stringField).isEqualTo("x");
assertEquals(2, value.longField); assertThat(value.longField).isEqualTo(2);
} }
@Test @Test
@ -149,7 +146,7 @@ public class ExclusionStrategyFunctionalTest {
.create(); .create();
String json = "{\"annotatedField\":1,\"stringField\":\"x\",\"longField\":2}"; String json = "{\"annotatedField\":1,\"stringField\":\"x\",\"longField\":2}";
SampleObjectForTest value = gson.fromJson(json, SampleObjectForTest.class); SampleObjectForTest value = gson.fromJson(json, SampleObjectForTest.class);
assertNull(value); assertThat(value).isNull();
} }
@Test @Test
@ -158,9 +155,9 @@ public class ExclusionStrategyFunctionalTest {
.addDeserializationExclusionStrategy(EXCLUDE_SAMPLE_OBJECT_FOR_TEST) .addDeserializationExclusionStrategy(EXCLUDE_SAMPLE_OBJECT_FOR_TEST)
.create(); .create();
String json = gson.toJson(new SampleObjectForTest(), SampleObjectForTest.class); String json = gson.toJson(new SampleObjectForTest(), SampleObjectForTest.class);
assertTrue(json.contains("\"stringField\"")); assertThat(json).contains("\"stringField\"");
assertTrue(json.contains("\"annotatedField\"")); assertThat(json).contains("\"annotatedField\"");
assertTrue(json.contains("\"longField\"")); assertThat(json).contains("\"longField\"");
} }
private static Gson createGson(ExclusionStrategy exclusionStrategy, boolean serialization) { private static Gson createGson(ExclusionStrategy exclusionStrategy, boolean serialization) {

View File

@ -16,10 +16,7 @@
package com.google.gson.functional; package com.google.gson.functional;
import static org.junit.Assert.assertEquals; import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;
@ -47,15 +44,15 @@ public class ExposeFieldsTest {
} }
@Test @Test
public void testNullExposeFieldSerialization() throws Exception { public void testNullExposeFieldSerialization() {
ClassWithExposedFields object = new ClassWithExposedFields(null, 1); ClassWithExposedFields object = new ClassWithExposedFields(null, 1);
String json = gson.toJson(object); String json = gson.toJson(object);
assertEquals(object.getExpectedJson(), json); assertThat(json).isEqualTo(object.getExpectedJson());
} }
@Test @Test
public void testArrayWithOneNullExposeFieldObjectSerialization() throws Exception { public void testArrayWithOneNullExposeFieldObjectSerialization() {
ClassWithExposedFields object1 = new ClassWithExposedFields(1, 1); ClassWithExposedFields object1 = new ClassWithExposedFields(1, 1);
ClassWithExposedFields object2 = new ClassWithExposedFields(null, 1); ClassWithExposedFields object2 = new ClassWithExposedFields(null, 1);
ClassWithExposedFields object3 = new ClassWithExposedFields(2, 2); ClassWithExposedFields object3 = new ClassWithExposedFields(2, 2);
@ -68,57 +65,57 @@ public class ExposeFieldsTest {
.append(object3.getExpectedJson()).append(']') .append(object3.getExpectedJson()).append(']')
.toString(); .toString();
assertEquals(expected, json); assertThat(json).isEqualTo(expected);
} }
@Test @Test
public void testExposeAnnotationSerialization() throws Exception { public void testExposeAnnotationSerialization() {
ClassWithExposedFields target = new ClassWithExposedFields(1, 2); ClassWithExposedFields target = new ClassWithExposedFields(1, 2);
assertEquals(target.getExpectedJson(), gson.toJson(target)); assertThat(gson.toJson(target)).isEqualTo(target.getExpectedJson());
} }
@Test @Test
public void testExposeAnnotationDeserialization() throws Exception { public void testExposeAnnotationDeserialization() {
String json = "{a:3,b:4,d:20.0}"; String json = "{a:3,b:4,d:20.0}";
ClassWithExposedFields target = gson.fromJson(json, ClassWithExposedFields.class); ClassWithExposedFields target = gson.fromJson(json, ClassWithExposedFields.class);
assertEquals(3, (int) target.a); assertThat(target.a).isEqualTo(3);
assertNull(target.b); assertThat(target.b).isNull();
assertFalse(target.d == 20); assertThat(target.d).isNotEqualTo(20);
} }
@Test @Test
public void testNoExposedFieldSerialization() throws Exception { public void testNoExposedFieldSerialization() {
ClassWithNoExposedFields obj = new ClassWithNoExposedFields(); ClassWithNoExposedFields obj = new ClassWithNoExposedFields();
String json = gson.toJson(obj); String json = gson.toJson(obj);
assertEquals("{}", json); assertThat(json).isEqualTo("{}");
} }
@Test @Test
public void testNoExposedFieldDeserialization() throws Exception { public void testNoExposedFieldDeserialization() {
String json = "{a:4,b:5}"; String json = "{a:4,b:5}";
ClassWithNoExposedFields obj = gson.fromJson(json, ClassWithNoExposedFields.class); ClassWithNoExposedFields obj = gson.fromJson(json, ClassWithNoExposedFields.class);
assertEquals(0, obj.a); assertThat(obj.a).isEqualTo(0);
assertEquals(1, obj.b); assertThat(obj.b).isEqualTo(1);
} }
@Test @Test
public void testExposedInterfaceFieldSerialization() throws Exception { public void testExposedInterfaceFieldSerialization() {
String expected = "{\"interfaceField\":{}}"; String expected = "{\"interfaceField\":{}}";
ClassWithInterfaceField target = new ClassWithInterfaceField(new SomeObject()); ClassWithInterfaceField target = new ClassWithInterfaceField(new SomeObject());
String actual = gson.toJson(target); String actual = gson.toJson(target);
assertEquals(expected, actual); assertThat(actual).isEqualTo(expected);
} }
@Test @Test
public void testExposedInterfaceFieldDeserialization() throws Exception { public void testExposedInterfaceFieldDeserialization() {
String json = "{\"interfaceField\":{}}"; String json = "{\"interfaceField\":{}}";
ClassWithInterfaceField obj = gson.fromJson(json, ClassWithInterfaceField.class); ClassWithInterfaceField obj = gson.fromJson(json, ClassWithInterfaceField.class);
assertNotNull(obj.interfaceField); assertThat(obj.interfaceField).isNotNull();
} }
private static class ClassWithExposedFields { private static class ClassWithExposedFields {

View File

@ -16,7 +16,7 @@
package com.google.gson.functional; 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.Gson;
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;
@ -41,37 +41,37 @@ public class FieldExclusionTest {
} }
@Test @Test
public void testDefaultInnerClassExclusion() throws Exception { public void testDefaultInnerClassExclusion() {
Gson gson = new Gson(); Gson gson = new Gson();
Outer.Inner target = outer.new Inner(VALUE); Outer.Inner target = outer.new Inner(VALUE);
String result = gson.toJson(target); String result = gson.toJson(target);
assertEquals(target.toJson(), result); assertThat(result).isEqualTo(target.toJson());
gson = new GsonBuilder().create(); gson = new GsonBuilder().create();
target = outer.new Inner(VALUE); target = outer.new Inner(VALUE);
result = gson.toJson(target); result = gson.toJson(target);
assertEquals(target.toJson(), result); assertThat(result).isEqualTo(target.toJson());
} }
@Test @Test
public void testInnerClassExclusion() throws Exception { public void testInnerClassExclusion() {
Gson gson = new GsonBuilder().disableInnerClassSerialization().create(); Gson gson = new GsonBuilder().disableInnerClassSerialization().create();
Outer.Inner target = outer.new Inner(VALUE); Outer.Inner target = outer.new Inner(VALUE);
String result = gson.toJson(target); String result = gson.toJson(target);
assertEquals("null", result); assertThat(result).isEqualTo("null");
} }
@Test @Test
public void testDefaultNestedStaticClassIncluded() throws Exception { public void testDefaultNestedStaticClassIncluded() {
Gson gson = new Gson(); Gson gson = new Gson();
Outer.Inner target = outer.new Inner(VALUE); Outer.Inner target = outer.new Inner(VALUE);
String result = gson.toJson(target); String result = gson.toJson(target);
assertEquals(target.toJson(), result); assertThat(result).isEqualTo(target.toJson());
gson = new GsonBuilder().create(); gson = new GsonBuilder().create();
target = outer.new Inner(VALUE); target = outer.new Inner(VALUE);
result = gson.toJson(target); result = gson.toJson(target);
assertEquals(target.toJson(), result); assertThat(result).isEqualTo(target.toJson());
} }
private static class Outer { private static class Outer {

View File

@ -22,7 +22,7 @@ import static com.google.gson.FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES;
import static com.google.gson.FieldNamingPolicy.UPPER_CAMEL_CASE; import static com.google.gson.FieldNamingPolicy.UPPER_CAMEL_CASE;
import static com.google.gson.FieldNamingPolicy.UPPER_CAMEL_CASE_WITH_SPACES; import static com.google.gson.FieldNamingPolicy.UPPER_CAMEL_CASE_WITH_SPACES;
import static com.google.gson.FieldNamingPolicy.UPPER_CASE_WITH_UNDERSCORES; import static com.google.gson.FieldNamingPolicy.UPPER_CASE_WITH_UNDERSCORES;
import static org.junit.Assert.assertEquals; import static com.google.common.truth.Truth.assertThat;
import com.google.gson.FieldNamingPolicy; import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson; import com.google.gson.Gson;
@ -34,55 +34,55 @@ public final class FieldNamingTest {
@Test @Test
public void testIdentity() { public void testIdentity() {
Gson gson = getGsonWithNamingPolicy(IDENTITY); Gson gson = getGsonWithNamingPolicy(IDENTITY);
assertEquals("{'lowerCamel':1,'UpperCamel':2,'_lowerCamelLeadingUnderscore':3," + assertThat(gson.toJson(new TestNames()).replace('\"', '\''))
.isEqualTo("{'lowerCamel':1,'UpperCamel':2,'_lowerCamelLeadingUnderscore':3," +
"'_UpperCamelLeadingUnderscore':4,'lower_words':5,'UPPER_WORDS':6," + "'_UpperCamelLeadingUnderscore':4,'lower_words':5,'UPPER_WORDS':6," +
"'annotatedName':7,'lowerId':8,'_9':9}", "'annotatedName':7,'lowerId':8,'_9':9}");
gson.toJson(new TestNames()).replace('\"', '\''));
} }
@Test @Test
public void testUpperCamelCase() { public void testUpperCamelCase() {
Gson gson = getGsonWithNamingPolicy(UPPER_CAMEL_CASE); Gson gson = getGsonWithNamingPolicy(UPPER_CAMEL_CASE);
assertEquals("{'LowerCamel':1,'UpperCamel':2,'_LowerCamelLeadingUnderscore':3," + assertThat(gson.toJson(new TestNames()).replace('\"', '\''))
.isEqualTo("{'LowerCamel':1,'UpperCamel':2,'_LowerCamelLeadingUnderscore':3," +
"'_UpperCamelLeadingUnderscore':4,'Lower_words':5,'UPPER_WORDS':6," + "'_UpperCamelLeadingUnderscore':4,'Lower_words':5,'UPPER_WORDS':6," +
"'annotatedName':7,'LowerId':8,'_9':9}", "'annotatedName':7,'LowerId':8,'_9':9}");
gson.toJson(new TestNames()).replace('\"', '\''));
} }
@Test @Test
public void testUpperCamelCaseWithSpaces() { public void testUpperCamelCaseWithSpaces() {
Gson gson = getGsonWithNamingPolicy(UPPER_CAMEL_CASE_WITH_SPACES); Gson gson = getGsonWithNamingPolicy(UPPER_CAMEL_CASE_WITH_SPACES);
assertEquals("{'Lower Camel':1,'Upper Camel':2,'_Lower Camel Leading Underscore':3," + assertThat(gson.toJson(new TestNames()).replace('\"', '\''))
.isEqualTo("{'Lower Camel':1,'Upper Camel':2,'_Lower Camel Leading Underscore':3," +
"'_ Upper Camel Leading Underscore':4,'Lower_words':5,'U P P E R_ W O R D S':6," + "'_ Upper Camel Leading Underscore':4,'Lower_words':5,'U P P E R_ W O R D S':6," +
"'annotatedName':7,'Lower Id':8,'_9':9}", "'annotatedName':7,'Lower Id':8,'_9':9}");
gson.toJson(new TestNames()).replace('\"', '\''));
} }
@Test @Test
public void testUpperCaseWithUnderscores() { public void testUpperCaseWithUnderscores() {
Gson gson = getGsonWithNamingPolicy(UPPER_CASE_WITH_UNDERSCORES); Gson gson = getGsonWithNamingPolicy(UPPER_CASE_WITH_UNDERSCORES);
assertEquals("{'LOWER_CAMEL':1,'UPPER_CAMEL':2,'_LOWER_CAMEL_LEADING_UNDERSCORE':3," + assertThat(gson.toJson(new TestNames()).replace('\"', '\''))
.isEqualTo("{'LOWER_CAMEL':1,'UPPER_CAMEL':2,'_LOWER_CAMEL_LEADING_UNDERSCORE':3," +
"'__UPPER_CAMEL_LEADING_UNDERSCORE':4,'LOWER_WORDS':5,'U_P_P_E_R__W_O_R_D_S':6," + "'__UPPER_CAMEL_LEADING_UNDERSCORE':4,'LOWER_WORDS':5,'U_P_P_E_R__W_O_R_D_S':6," +
"'annotatedName':7,'LOWER_ID':8,'_9':9}", "'annotatedName':7,'LOWER_ID':8,'_9':9}");
gson.toJson(new TestNames()).replace('\"', '\''));
} }
@Test @Test
public void testLowerCaseWithUnderscores() { public void testLowerCaseWithUnderscores() {
Gson gson = getGsonWithNamingPolicy(LOWER_CASE_WITH_UNDERSCORES); Gson gson = getGsonWithNamingPolicy(LOWER_CASE_WITH_UNDERSCORES);
assertEquals("{'lower_camel':1,'upper_camel':2,'_lower_camel_leading_underscore':3," + assertThat(gson.toJson(new TestNames()).replace('\"', '\''))
.isEqualTo("{'lower_camel':1,'upper_camel':2,'_lower_camel_leading_underscore':3," +
"'__upper_camel_leading_underscore':4,'lower_words':5,'u_p_p_e_r__w_o_r_d_s':6," + "'__upper_camel_leading_underscore':4,'lower_words':5,'u_p_p_e_r__w_o_r_d_s':6," +
"'annotatedName':7,'lower_id':8,'_9':9}", "'annotatedName':7,'lower_id':8,'_9':9}");
gson.toJson(new TestNames()).replace('\"', '\''));
} }
@Test @Test
public void testLowerCaseWithDashes() { public void testLowerCaseWithDashes() {
Gson gson = getGsonWithNamingPolicy(LOWER_CASE_WITH_DASHES); Gson gson = getGsonWithNamingPolicy(LOWER_CASE_WITH_DASHES);
assertEquals("{'lower-camel':1,'upper-camel':2,'_lower-camel-leading-underscore':3," + assertThat(gson.toJson(new TestNames()).replace('\"', '\''))
.isEqualTo("{'lower-camel':1,'upper-camel':2,'_lower-camel-leading-underscore':3," +
"'_-upper-camel-leading-underscore':4,'lower_words':5,'u-p-p-e-r_-w-o-r-d-s':6," + "'_-upper-camel-leading-underscore':4,'lower_words':5,'u-p-p-e-r_-w-o-r-d-s':6," +
"'annotatedName':7,'lower-id':8,'_9':9}", "'annotatedName':7,'lower-id':8,'_9':9}");
gson.toJson(new TestNames()).replace('\"', '\''));
} }
private Gson getGsonWithNamingPolicy(FieldNamingPolicy fieldNamingPolicy){ private Gson getGsonWithNamingPolicy(FieldNamingPolicy fieldNamingPolicy){

View File

@ -15,7 +15,7 @@
*/ */
package com.google.gson.functional; package com.google.gson.functional;
import static org.junit.Assert.assertTrue; import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import com.google.gson.Gson; import com.google.gson.Gson;
@ -54,8 +54,8 @@ public class GsonVersionDiagnosticsTest {
@Test @Test
public void testVersionPattern() { public void testVersionPattern() {
assertTrue(GSON_VERSION_PATTERN.matcher("(GSON 2.8.5)").matches()); assertThat(GSON_VERSION_PATTERN.matcher("(GSON 2.8.5)").matches()).isTrue();
assertTrue(GSON_VERSION_PATTERN.matcher("(GSON 2.8.5-SNAPSHOT)").matches()); assertThat(GSON_VERSION_PATTERN.matcher("(GSON 2.8.5-SNAPSHOT)").matches()).isTrue();
} }
@Test @Test
@ -82,12 +82,12 @@ public class GsonVersionDiagnosticsTest {
String msg = expected.getMessage(); String msg = expected.getMessage();
// System.err.println(msg); // System.err.println(msg);
int start = msg.indexOf("(GSON"); int start = msg.indexOf("(GSON");
assertTrue(start > 0); assertThat(start > 0).isTrue();
int end = msg.indexOf("):") + 1; int end = msg.indexOf("):") + 1;
assertTrue(end > 0 && end > start + 6); assertThat(end > 0 && end > start + 6).isTrue();
String version = msg.substring(start, end); String version = msg.substring(start, end);
// System.err.println(version); // System.err.println(version);
assertTrue(GSON_VERSION_PATTERN.matcher(version).matches()); assertThat(GSON_VERSION_PATTERN.matcher(version).matches()).isTrue();
} }
private static final class TestType { private static final class TestType {

View File

@ -15,10 +15,7 @@
*/ */
package com.google.gson.functional; package com.google.gson.functional;
import static org.junit.Assert.assertEquals; import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.JsonArray; import com.google.gson.JsonArray;
@ -58,20 +55,20 @@ public class InheritanceTest {
} }
@Test @Test
public void testSubClassSerialization() throws Exception { public void testSubClassSerialization() {
SubTypeOfNested target = new SubTypeOfNested(new BagOfPrimitives(10, 20, false, "stringValue"), SubTypeOfNested target = new SubTypeOfNested(new BagOfPrimitives(10, 20, false, "stringValue"),
new BagOfPrimitives(30, 40, true, "stringValue")); new BagOfPrimitives(30, 40, true, "stringValue"));
assertEquals(target.getExpectedJson(), gson.toJson(target)); assertThat(gson.toJson(target)).isEqualTo(target.getExpectedJson());
} }
@Test @Test
public void testSubClassDeserialization() throws Exception { public void testSubClassDeserialization() {
String json = "{\"value\":5,\"primitive1\":{\"longValue\":10,\"intValue\":20," String json = "{\"value\":5,\"primitive1\":{\"longValue\":10,\"intValue\":20,"
+ "\"booleanValue\":false,\"stringValue\":\"stringValue\"},\"primitive2\":" + "\"booleanValue\":false,\"stringValue\":\"stringValue\"},\"primitive2\":"
+ "{\"longValue\":30,\"intValue\":40,\"booleanValue\":true," + "{\"longValue\":30,\"intValue\":40,\"booleanValue\":true,"
+ "\"stringValue\":\"stringValue\"}}"; + "\"stringValue\":\"stringValue\"}}";
SubTypeOfNested target = gson.fromJson(json, SubTypeOfNested.class); SubTypeOfNested target = gson.fromJson(json, SubTypeOfNested.class);
assertEquals(json, target.getExpectedJson()); assertThat(target.getExpectedJson()).isEqualTo(json);
} }
@Test @Test
@ -79,7 +76,7 @@ public class InheritanceTest {
ClassWithBaseField sub = new ClassWithBaseField(new Sub()); ClassWithBaseField sub = new ClassWithBaseField(new Sub());
JsonObject json = (JsonObject) gson.toJsonTree(sub); JsonObject json = (JsonObject) gson.toJsonTree(sub);
JsonElement base = json.getAsJsonObject().get(ClassWithBaseField.FIELD_KEY); JsonElement base = json.getAsJsonObject().get(ClassWithBaseField.FIELD_KEY);
assertEquals(Sub.SUB_NAME, base.getAsJsonObject().get(Sub.SUB_FIELD_KEY).getAsString()); assertThat(base.getAsJsonObject().get(Sub.SUB_FIELD_KEY).getAsString()).isEqualTo(Sub.SUB_NAME);
} }
@Test @Test
@ -89,7 +86,7 @@ public class InheritanceTest {
JsonObject json = gson.toJsonTree(sub).getAsJsonObject(); JsonObject json = gson.toJsonTree(sub).getAsJsonObject();
JsonArray bases = json.get(ClassWithBaseArrayField.FIELD_KEY).getAsJsonArray(); JsonArray bases = json.get(ClassWithBaseArrayField.FIELD_KEY).getAsJsonArray();
for (JsonElement element : bases) { for (JsonElement element : bases) {
assertEquals(Sub.SUB_NAME, element.getAsJsonObject().get(Sub.SUB_FIELD_KEY).getAsString()); assertThat(element.getAsJsonObject().get(Sub.SUB_FIELD_KEY).getAsString()).isEqualTo(Sub.SUB_NAME);
} }
} }
@ -102,7 +99,7 @@ public class InheritanceTest {
JsonObject json = gson.toJsonTree(sub).getAsJsonObject(); JsonObject json = gson.toJsonTree(sub).getAsJsonObject();
JsonArray bases = json.get(ClassWithBaseArrayField.FIELD_KEY).getAsJsonArray(); JsonArray bases = json.get(ClassWithBaseArrayField.FIELD_KEY).getAsJsonArray();
for (JsonElement element : bases) { for (JsonElement element : bases) {
assertEquals(Sub.SUB_NAME, element.getAsJsonObject().get(Sub.SUB_FIELD_KEY).getAsString()); assertThat(element.getAsJsonObject().get(Sub.SUB_FIELD_KEY).getAsString()).isEqualTo(Sub.SUB_NAME);
} }
} }
@ -110,44 +107,44 @@ public class InheritanceTest {
public void testBaseSerializedAsSub() { public void testBaseSerializedAsSub() {
Base base = new Sub(); Base base = new Sub();
JsonObject json = gson.toJsonTree(base).getAsJsonObject(); JsonObject json = gson.toJsonTree(base).getAsJsonObject();
assertEquals(Sub.SUB_NAME, json.get(Sub.SUB_FIELD_KEY).getAsString()); assertThat(json.get(Sub.SUB_FIELD_KEY).getAsString()).isEqualTo(Sub.SUB_NAME);
} }
@Test @Test
public void testBaseSerializedAsSubForToJsonMethod() { public void testBaseSerializedAsSubForToJsonMethod() {
Base base = new Sub(); Base base = new Sub();
String json = gson.toJson(base); String json = gson.toJson(base);
assertTrue(json.contains(Sub.SUB_NAME)); assertThat(json).contains(Sub.SUB_NAME);
} }
@Test @Test
public void testBaseSerializedAsBaseWhenSpecifiedWithExplicitType() { public void testBaseSerializedAsBaseWhenSpecifiedWithExplicitType() {
Base base = new Sub(); Base base = new Sub();
JsonObject json = gson.toJsonTree(base, Base.class).getAsJsonObject(); JsonObject json = gson.toJsonTree(base, Base.class).getAsJsonObject();
assertEquals(Base.BASE_NAME, json.get(Base.BASE_FIELD_KEY).getAsString()); assertThat(json.get(Base.BASE_FIELD_KEY).getAsString()).isEqualTo(Base.BASE_NAME);
assertNull(json.get(Sub.SUB_FIELD_KEY)); assertThat(json.get(Sub.SUB_FIELD_KEY)).isNull();
} }
@Test @Test
public void testBaseSerializedAsBaseWhenSpecifiedWithExplicitTypeForToJsonMethod() { public void testBaseSerializedAsBaseWhenSpecifiedWithExplicitTypeForToJsonMethod() {
Base base = new Sub(); Base base = new Sub();
String json = gson.toJson(base, Base.class); String json = gson.toJson(base, Base.class);
assertTrue(json.contains(Base.BASE_NAME)); assertThat(json).contains(Base.BASE_NAME);
assertFalse(json.contains(Sub.SUB_FIELD_KEY)); assertThat(json).doesNotContain(Sub.SUB_FIELD_KEY);
} }
@Test @Test
public void testBaseSerializedAsSubWhenSpecifiedWithExplicitType() { public void testBaseSerializedAsSubWhenSpecifiedWithExplicitType() {
Base base = new Sub(); Base base = new Sub();
JsonObject json = gson.toJsonTree(base, Sub.class).getAsJsonObject(); JsonObject json = gson.toJsonTree(base, Sub.class).getAsJsonObject();
assertEquals(Sub.SUB_NAME, json.get(Sub.SUB_FIELD_KEY).getAsString()); assertThat(json.get(Sub.SUB_FIELD_KEY).getAsString()).isEqualTo(Sub.SUB_NAME);
} }
@Test @Test
public void testBaseSerializedAsSubWhenSpecifiedWithExplicitTypeForToJsonMethod() { public void testBaseSerializedAsSubWhenSpecifiedWithExplicitTypeForToJsonMethod() {
Base base = new Sub(); Base base = new Sub();
String json = gson.toJson(base, Sub.class); String json = gson.toJson(base, Sub.class);
assertTrue(json.contains(Sub.SUB_NAME)); assertThat(json).contains(Sub.SUB_NAME);
} }
private static class SubTypeOfNested extends Nested { private static class SubTypeOfNested extends Nested {
@ -165,7 +162,7 @@ public class InheritanceTest {
} }
@Test @Test
public void testSubInterfacesOfCollectionSerialization() throws Exception { public void testSubInterfacesOfCollectionSerialization() {
List<Integer> list = new LinkedList<>(); List<Integer> list = new LinkedList<>();
list.add(0); list.add(0);
list.add(1); list.add(1);
@ -188,20 +185,20 @@ public class InheritanceTest {
sortedSet.add('d'); sortedSet.add('d');
ClassWithSubInterfacesOfCollection target = ClassWithSubInterfacesOfCollection target =
new ClassWithSubInterfacesOfCollection(list, queue, set, sortedSet); new ClassWithSubInterfacesOfCollection(list, queue, set, sortedSet);
assertEquals(target.getExpectedJson(), gson.toJson(target)); assertThat(gson.toJson(target)).isEqualTo(target.getExpectedJson());
} }
@Test @Test
public void testSubInterfacesOfCollectionDeserialization() throws Exception { public void testSubInterfacesOfCollectionDeserialization() {
String json = "{\"list\":[0,1,2,3],\"queue\":[0,1,2,3],\"set\":[0.1,0.2,0.3,0.4]," String json = "{\"list\":[0,1,2,3],\"queue\":[0,1,2,3],\"set\":[0.1,0.2,0.3,0.4],"
+ "\"sortedSet\":[\"a\",\"b\",\"c\",\"d\"]" + "\"sortedSet\":[\"a\",\"b\",\"c\",\"d\"]"
+ "}"; + "}";
ClassWithSubInterfacesOfCollection target = ClassWithSubInterfacesOfCollection target =
gson.fromJson(json, ClassWithSubInterfacesOfCollection.class); gson.fromJson(json, ClassWithSubInterfacesOfCollection.class);
assertTrue(target.listContains(0, 1, 2, 3)); assertThat(target.listContains(0, 1, 2, 3)).isTrue();
assertTrue(target.queueContains(0, 1, 2, 3)); assertThat(target.queueContains(0, 1, 2, 3)).isTrue();
assertTrue(target.setContains(0.1F, 0.2F, 0.3F, 0.4F)); assertThat(target.setContains(0.1F, 0.2F, 0.3F, 0.4F)).isTrue();
assertTrue(target.sortedSetContains('a', 'b', 'c', 'd')); assertThat(target.sortedSetContains('a', 'b', 'c', 'd')).isTrue();
} }
private static class ClassWithSubInterfacesOfCollection { private static class ClassWithSubInterfacesOfCollection {

View File

@ -16,9 +16,7 @@
package com.google.gson.functional; package com.google.gson.functional;
import static org.junit.Assert.assertEquals; import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;
@ -53,7 +51,7 @@ public class InstanceCreatorTest {
.create(); .create();
String json = "{baseName:'BaseRevised',subName:'Sub'}"; String json = "{baseName:'BaseRevised',subName:'Sub'}";
Base base = gson.fromJson(json, Base.class); Base base = gson.fromJson(json, Base.class);
assertEquals("BaseRevised", base.baseName); assertThat(base.baseName).isEqualTo("BaseRevised");
} }
@Test @Test
@ -68,11 +66,11 @@ public class InstanceCreatorTest {
String json = "{baseName:'Base',subName:'SubRevised'}"; String json = "{baseName:'Base',subName:'SubRevised'}";
Base base = gson.fromJson(json, Base.class); Base base = gson.fromJson(json, Base.class);
assertTrue(base instanceof Sub); assertThat(base instanceof Sub).isTrue();
Sub sub = (Sub) base; Sub sub = (Sub) base;
assertFalse("SubRevised".equals(sub.subName)); assertThat("SubRevised".equals(sub.subName)).isFalse();
assertEquals(Sub.SUB_NAME, sub.subName); assertThat(sub.subName).isEqualTo(Sub.SUB_NAME);
} }
@Test @Test
@ -86,8 +84,8 @@ public class InstanceCreatorTest {
.create(); .create();
String json = "{base:{baseName:'Base',subName:'SubRevised'}}"; String json = "{base:{baseName:'Base',subName:'SubRevised'}}";
ClassWithBaseField target = gson.fromJson(json, ClassWithBaseField.class); ClassWithBaseField target = gson.fromJson(json, ClassWithBaseField.class);
assertTrue(target.base instanceof Sub); assertThat(target.base instanceof Sub).isTrue();
assertEquals(Sub.SUB_NAME, ((Sub)target.base).subName); assertThat(((Sub)target.base).subName).isEqualTo(Sub.SUB_NAME);
} }
// This regressed in Gson 2.0 and 2.1 // This regressed in Gson 2.0 and 2.1
@ -105,12 +103,12 @@ public class InstanceCreatorTest {
.registerTypeAdapter(listOfStringType, listCreator) .registerTypeAdapter(listOfStringType, listCreator)
.create(); .create();
List<String> list = gson.fromJson("[\"a\"]", listOfStringType); List<String> list = gson.fromJson("[\"a\"]", listOfStringType);
assertEquals(SubArrayList.class, list.getClass()); assertThat(list.getClass()).isEqualTo(SubArrayList.class);
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@Test @Test
public void testInstanceCreatorForParametrizedType() throws Exception { public void testInstanceCreatorForParametrizedType() {
@SuppressWarnings("serial") @SuppressWarnings("serial")
class SubTreeSet<T> extends TreeSet<T> {} class SubTreeSet<T> extends TreeSet<T> {}
InstanceCreator<SortedSet<?>> sortedSetCreator = new InstanceCreator<SortedSet<?>>() { InstanceCreator<SortedSet<?>> sortedSetCreator = new InstanceCreator<SortedSet<?>>() {
@ -124,11 +122,11 @@ public class InstanceCreatorTest {
Type sortedSetType = new TypeToken<SortedSet<String>>() {}.getType(); Type sortedSetType = new TypeToken<SortedSet<String>>() {}.getType();
SortedSet<String> set = gson.fromJson("[\"a\"]", sortedSetType); SortedSet<String> set = gson.fromJson("[\"a\"]", sortedSetType);
assertEquals(set.first(), "a"); assertThat("a").isEqualTo(set.first());
assertEquals(SubTreeSet.class, set.getClass()); assertThat(set.getClass()).isEqualTo(SubTreeSet.class);
set = gson.fromJson("[\"b\"]", SortedSet.class); set = gson.fromJson("[\"b\"]", SortedSet.class);
assertEquals(set.first(), "b"); assertThat("b").isEqualTo(set.first());
assertEquals(SubTreeSet.class, set.getClass()); assertThat(set.getClass()).isEqualTo(SubTreeSet.class);
} }
} }

View File

@ -16,7 +16,7 @@
package com.google.gson.functional; 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.Gson;
import org.junit.Before; import org.junit.Before;
@ -41,14 +41,14 @@ public class InterfaceTest {
} }
@Test @Test
public void testSerializingObjectImplementingInterface() throws Exception { public void testSerializingObjectImplementingInterface() {
assertEquals(OBJ_JSON, gson.toJson(obj)); assertThat(gson.toJson(obj)).isEqualTo(OBJ_JSON);
} }
@Test @Test
public void testSerializingInterfaceObjectField() throws Exception { public void testSerializingInterfaceObjectField() {
TestObjectWrapper objWrapper = new TestObjectWrapper(obj); TestObjectWrapper objWrapper = new TestObjectWrapper(obj);
assertEquals("{\"obj\":" + OBJ_JSON + "}", gson.toJson(objWrapper)); assertThat(gson.toJson(objWrapper)).isEqualTo("{\"obj\":" + OBJ_JSON + "}");
} }
private static interface TestObjectInterface { private static interface TestObjectInterface {

View File

@ -16,7 +16,7 @@
package com.google.gson.functional; 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.Gson;
import org.junit.Before; import org.junit.Before;
@ -36,48 +36,48 @@ public class InternationalizationTest {
} }
@Test @Test
public void testStringsWithUnicodeChineseCharactersSerialization() throws Exception { public void testStringsWithUnicodeChineseCharactersSerialization() {
String target = "\u597d\u597d\u597d"; String target = "\u597d\u597d\u597d";
String json = gson.toJson(target); String json = gson.toJson(target);
String expected = '"' + target + '"'; String expected = '"' + target + '"';
assertEquals(expected, json); assertThat(json).isEqualTo(expected);
} }
@Test @Test
public void testStringsWithUnicodeChineseCharactersDeserialization() throws Exception { public void testStringsWithUnicodeChineseCharactersDeserialization() {
String expected = "\u597d\u597d\u597d"; String expected = "\u597d\u597d\u597d";
String json = '"' + expected + '"'; String json = '"' + expected + '"';
String actual = gson.fromJson(json, String.class); String actual = gson.fromJson(json, String.class);
assertEquals(expected, actual); assertThat(actual).isEqualTo(expected);
} }
@Test @Test
public void testStringsWithUnicodeChineseCharactersEscapedDeserialization() throws Exception { public void testStringsWithUnicodeChineseCharactersEscapedDeserialization() {
String actual = gson.fromJson("'\\u597d\\u597d\\u597d'", String.class); String actual = gson.fromJson("'\\u597d\\u597d\\u597d'", String.class);
assertEquals("\u597d\u597d\u597d", actual); assertThat(actual).isEqualTo("\u597d\u597d\u597d");
} }
@Test @Test
public void testSupplementaryUnicodeSerialization() throws Exception { public void testSupplementaryUnicodeSerialization() {
// Supplementary code point U+1F60A // Supplementary code point U+1F60A
String supplementaryCodePoint = new String(new int[] {0x1F60A}, 0, 1); String supplementaryCodePoint = new String(new int[] {0x1F60A}, 0, 1);
String json = gson.toJson(supplementaryCodePoint); String json = gson.toJson(supplementaryCodePoint);
assertEquals('"' + supplementaryCodePoint + '"', json); assertThat(json).isEqualTo('"' + supplementaryCodePoint + '"');
} }
@Test @Test
public void testSupplementaryUnicodeDeserialization() throws Exception { public void testSupplementaryUnicodeDeserialization() {
// Supplementary code point U+1F60A // Supplementary code point U+1F60A
String supplementaryCodePoint = new String(new int[] {0x1F60A}, 0, 1); String supplementaryCodePoint = new String(new int[] {0x1F60A}, 0, 1);
String actual = gson.fromJson('"' + supplementaryCodePoint + '"', String.class); String actual = gson.fromJson('"' + supplementaryCodePoint + '"', String.class);
assertEquals(supplementaryCodePoint, actual); assertThat(actual).isEqualTo(supplementaryCodePoint);
} }
@Test @Test
public void testSupplementaryUnicodeEscapedDeserialization() throws Exception { public void testSupplementaryUnicodeEscapedDeserialization() {
// Supplementary code point U+1F60A // Supplementary code point U+1F60A
String supplementaryCodePoint = new String(new int[] {0x1F60A}, 0, 1); String supplementaryCodePoint = new String(new int[] {0x1F60A}, 0, 1);
String actual = gson.fromJson("\"\\uD83D\\uDE0A\"", String.class); String actual = gson.fromJson("\"\\uD83D\\uDE0A\"", String.class);
assertEquals(supplementaryCodePoint, actual); assertThat(actual).isEqualTo(supplementaryCodePoint);
} }
} }

View File

@ -15,10 +15,7 @@
*/ */
package com.google.gson.functional; package com.google.gson.functional;
import static org.junit.Assert.assertEquals; import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertThrows;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
@ -55,24 +52,24 @@ public final class Java17RecordTest {
public void testFirstNameIsChosenForSerialization() { public void testFirstNameIsChosenForSerialization() {
RecordWithCustomNames target = new RecordWithCustomNames("v1", "v2"); RecordWithCustomNames target = new RecordWithCustomNames("v1", "v2");
// Ensure name1 occurs exactly once, and name2 and name3 don't appear // 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 @Test
public void testMultipleNamesDeserializedCorrectly() { public void testMultipleNamesDeserializedCorrectly() {
assertEquals("v1", gson.fromJson("{'name':'v1'}", RecordWithCustomNames.class).a); assertThat(gson.fromJson("{'name':'v1'}", RecordWithCustomNames.class).a).isEqualTo("v1");
// Both name1 and name2 gets deserialized to b // Both name1 and name2 gets deserialized to b
assertEquals("v11", gson.fromJson("{'name': 'v1', 'name1':'v11'}", RecordWithCustomNames.class).b); assertThat(gson.fromJson("{'name': 'v1', 'name1':'v11'}", RecordWithCustomNames.class).b).isEqualTo("v11");
assertEquals("v2", gson.fromJson("{'name': 'v1', 'name2':'v2'}", RecordWithCustomNames.class).b); assertThat(gson.fromJson("{'name': 'v1', 'name2':'v2'}", RecordWithCustomNames.class).b).isEqualTo("v2");
assertEquals("v3", gson.fromJson("{'name': 'v1', 'name3':'v3'}", RecordWithCustomNames.class).b); assertThat(gson.fromJson("{'name': 'v1', 'name3':'v3'}", RecordWithCustomNames.class).b).isEqualTo("v3");
} }
@Test @Test
public void testMultipleNamesInTheSameString() { public void testMultipleNamesInTheSameString() {
// The last value takes precedence // The last value takes precedence
assertEquals("v3", assertThat(gson.fromJson("{'name': 'foo', 'name1':'v1','name2':'v2','name3':'v3'}", RecordWithCustomNames.class).b)
gson.fromJson("{'name': 'foo', 'name1':'v1','name2':'v2','name3':'v3'}", RecordWithCustomNames.class).b); .isEqualTo("v3");
} }
private record RecordWithCustomNames( private record RecordWithCustomNames(
@ -90,8 +87,8 @@ public final class Java17RecordTest {
} }
var exception = assertThrows(JsonIOException.class, () -> gson.getAdapter(LocalRecord.class)); var exception = assertThrows(JsonIOException.class, () -> gson.getAdapter(LocalRecord.class));
assertEquals("@SerializedName on method '" + LocalRecord.class.getName() + "#i()' is not supported", assertThat(exception).hasMessageThat()
exception.getMessage()); .isEqualTo("@SerializedName on method '" + LocalRecord.class.getName() + "#i()' is not supported");
} }
@Test @Test
@ -102,8 +99,8 @@ public final class Java17RecordTest {
.setFieldNamingStrategy(f -> f.getName() + "-custom") .setFieldNamingStrategy(f -> f.getName() + "-custom")
.create(); .create();
assertEquals("{\"i-custom\":1}", gson.toJson(new LocalRecord(1))); assertThat(gson.toJson(new LocalRecord(1))).isEqualTo("{\"i-custom\":1}");
assertEquals(new LocalRecord(2), gson.fromJson("{\"i-custom\":2}", LocalRecord.class)); assertThat(gson.fromJson("{\"i-custom\":2}", LocalRecord.class)).isEqualTo(new LocalRecord(2));
} }
@Test @Test
@ -111,7 +108,7 @@ public final class Java17RecordTest {
record LocalRecord(int i) {} record LocalRecord(int i) {}
// Unknown property 'x' should be ignored // Unknown property 'x' should be ignored
assertEquals(new LocalRecord(1), gson.fromJson("{\"i\":1,\"x\":2}", LocalRecord.class)); assertThat(gson.fromJson("{\"i\":1,\"x\":2}", LocalRecord.class)).isEqualTo(new LocalRecord(1));
} }
@Test @Test
@ -120,7 +117,7 @@ public final class Java17RecordTest {
String json = "{\"a\":null,\"a\":2,\"b\":1,\"b\":null}"; String json = "{\"a\":null,\"a\":2,\"b\":1,\"b\":null}";
// Should use value of last occurrence // Should use value of last occurrence
assertEquals(new LocalRecord(2, null), gson.fromJson(json, LocalRecord.class)); assertThat(gson.fromJson(json, LocalRecord.class)).isEqualTo(new LocalRecord(2, null));
} }
@Test @Test
@ -132,8 +129,8 @@ public final class Java17RecordTest {
} }
LocalRecord deserialized = gson.fromJson("{\"s\": null}", LocalRecord.class); LocalRecord deserialized = gson.fromJson("{\"s\": null}", LocalRecord.class);
assertEquals(new LocalRecord(null), deserialized); assertThat(deserialized).isEqualTo(new LocalRecord(null));
assertEquals("custom-null", deserialized.s()); assertThat(deserialized.s()).isEqualTo("custom-null");
} }
/** Tests behavior when the canonical constructor throws an exception */ /** Tests behavior when the canonical constructor throws an exception */
@ -154,9 +151,9 @@ public final class Java17RecordTest {
} }
// TODO: Adjust this once Gson throws more specific exception type // TODO: Adjust this once Gson throws more specific exception type
catch (RuntimeException e) { catch (RuntimeException e) {
assertEquals("Failed to invoke constructor '" + LocalRecord.class.getName() + "(String)' with args [value]", assertThat(e).hasMessageThat()
e.getMessage()); .isEqualTo("Failed to invoke constructor '" + LocalRecord.class.getName() + "(String)' with args [value]");
assertSame(LocalRecord.thrownException, e.getCause()); assertThat(e).hasCauseThat().isSameInstanceAs(LocalRecord.thrownException);
} }
} }
@ -169,7 +166,7 @@ public final class Java17RecordTest {
} }
} }
assertEquals("{\"s\":\"accessor-value\"}", gson.toJson(new LocalRecord(null))); assertThat(gson.toJson(new LocalRecord(null))).isEqualTo("{\"s\":\"accessor-value\"}");
} }
/** Tests behavior when a record accessor method throws an exception */ /** Tests behavior when a record accessor method throws an exception */
@ -188,9 +185,9 @@ public final class Java17RecordTest {
gson.toJson(new LocalRecord("a")); gson.toJson(new LocalRecord("a"));
fail(); fail();
} catch (JsonIOException e) { } catch (JsonIOException e) {
assertEquals("Accessor method '" + LocalRecord.class.getName() + "#s()' threw exception", assertThat(e).hasMessageThat()
e.getMessage()); .isEqualTo("Accessor method '" + LocalRecord.class.getName() + "#s()' threw exception");
assertSame(LocalRecord.thrownException, e.getCause()); assertThat(e).hasCauseThat().isSameInstanceAs(LocalRecord.thrownException);
} }
} }
@ -199,8 +196,8 @@ public final class Java17RecordTest {
public void testEmptyRecord() { public void testEmptyRecord() {
record EmptyRecord() {} record EmptyRecord() {}
assertEquals("{}", gson.toJson(new EmptyRecord())); assertThat(gson.toJson(new EmptyRecord())).isEqualTo("{}");
assertEquals(new EmptyRecord(), gson.fromJson("{}", EmptyRecord.class)); assertThat(gson.fromJson("{}", EmptyRecord.class)).isEqualTo(new EmptyRecord());
} }
/** /**
@ -212,22 +209,22 @@ public final class Java17RecordTest {
record LocalRecord(int i) {} record LocalRecord(int i) {}
TypeAdapter<LocalRecord> adapter = gson.getAdapter(LocalRecord.class); TypeAdapter<LocalRecord> adapter = gson.getAdapter(LocalRecord.class);
assertEquals("null", adapter.toJson(null)); assertThat(adapter.toJson(null)).isEqualTo("null");
assertNull(adapter.fromJson("null")); assertThat(adapter.fromJson("null")).isNull();
} }
@Test @Test
public void testPrimitiveDefaultValues() { public void testPrimitiveDefaultValues() {
RecordWithPrimitives expected = new RecordWithPrimitives("s", (byte) 0, (short) 0, 0, 0, 0, 0, '\0', false); RecordWithPrimitives expected = new RecordWithPrimitives("s", (byte) 0, (short) 0, 0, 0, 0, 0, '\0', false);
assertEquals(expected, gson.fromJson("{'aString': 's'}", RecordWithPrimitives.class)); assertThat(gson.fromJson("{'aString': 's'}", RecordWithPrimitives.class)).isEqualTo(expected);
} }
@Test @Test
public void testPrimitiveJsonNullValue() { public void testPrimitiveJsonNullValue() {
String s = "{'aString': 's', 'aByte': null, 'aShort': 0}"; String s = "{'aString': 's', 'aByte': null, 'aShort': 0}";
var e = assertThrows(JsonParseException.class, () -> gson.fromJson(s, RecordWithPrimitives.class)); var e = assertThrows(JsonParseException.class, () -> gson.fromJson(s, RecordWithPrimitives.class));
assertEquals("null is not allowed as value for record component 'aByte' of primitive type; at path $.aByte", assertThat(e).hasMessageThat()
e.getMessage()); .isEqualTo("null is not allowed as value for record component 'aByte' of primitive type; at path $.aByte");
} }
/** /**
@ -252,8 +249,8 @@ public final class Java17RecordTest {
String s = "{'aString': 's', 'aByte': 0}"; String s = "{'aString': 's', 'aByte': 0}";
var exception = assertThrows(JsonParseException.class, () -> gson.fromJson(s, RecordWithPrimitives.class)); var exception = assertThrows(JsonParseException.class, () -> gson.fromJson(s, RecordWithPrimitives.class));
assertEquals("null is not allowed as value for record component 'aByte' of primitive type; at path $.aByte", assertThat(exception).hasMessageThat()
exception.getMessage()); .isEqualTo("null is not allowed as value for record component 'aByte' of primitive type; at path $.aByte");
} }
private record RecordWithPrimitives( private record RecordWithPrimitives(
@ -264,7 +261,7 @@ public final class Java17RecordTest {
public void testObjectDefaultValue() { public void testObjectDefaultValue() {
record LocalRecord(String s, int i) {} record LocalRecord(String s, int i) {}
assertEquals(new LocalRecord(null, 1), gson.fromJson("{\"i\":1}", LocalRecord.class)); assertThat(gson.fromJson("{\"i\":1}", LocalRecord.class)).isEqualTo(new LocalRecord(null, 1));
} }
/** /**
@ -276,7 +273,7 @@ public final class Java17RecordTest {
@Test @Test
public void testStaticFieldSerialization() { public void testStaticFieldSerialization() {
// By default Gson should ignore static fields // By default Gson should ignore static fields
assertEquals("{}", gson.toJson(new RecordWithStaticField())); assertThat(gson.toJson(new RecordWithStaticField())).isEqualTo("{}");
Gson gson = new GsonBuilder() Gson gson = new GsonBuilder()
// Include static fields // Include static fields
@ -284,7 +281,7 @@ public final class Java17RecordTest {
.create(); .create();
String json = gson.toJson(new RecordWithStaticField()); String json = gson.toJson(new RecordWithStaticField());
assertEquals("{\"s\":\"initial\"}", json); assertThat(json).isEqualTo("{\"s\":\"initial\"}");
} }
/** /**
@ -297,7 +294,7 @@ public final class Java17RecordTest {
public void testStaticFieldDeserialization() { public void testStaticFieldDeserialization() {
// By default Gson should ignore static fields // By default Gson should ignore static fields
gson.fromJson("{\"s\":\"custom\"}", RecordWithStaticField.class); gson.fromJson("{\"s\":\"custom\"}", RecordWithStaticField.class);
assertEquals("initial", RecordWithStaticField.s); assertThat(RecordWithStaticField.s).isEqualTo("initial");
Gson gson = new GsonBuilder() Gson gson = new GsonBuilder()
// Include static fields // Include static fields
@ -307,9 +304,9 @@ public final class Java17RecordTest {
String oldValue = RecordWithStaticField.s; String oldValue = RecordWithStaticField.s;
try { try {
RecordWithStaticField obj = gson.fromJson("{\"s\":\"custom\"}", RecordWithStaticField.class); RecordWithStaticField obj = gson.fromJson("{\"s\":\"custom\"}", RecordWithStaticField.class);
assertNotNull(obj); assertThat(obj).isNotNull();
// Currently record deserialization always ignores static fields // Currently record deserialization always ignores static fields
assertEquals("initial", RecordWithStaticField.s); assertThat(RecordWithStaticField.s).isEqualTo("initial");
} finally { } finally {
RecordWithStaticField.s = oldValue; RecordWithStaticField.s = oldValue;
} }
@ -328,7 +325,7 @@ public final class Java17RecordTest {
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create(); Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
String json = gson.toJson(new RecordWithExpose(1, 2)); String json = gson.toJson(new RecordWithExpose(1, 2));
assertEquals("{\"a\":1}", json); assertThat(json).isEqualTo("{\"a\":1}");
} }
@Test @Test
@ -347,7 +344,7 @@ public final class Java17RecordTest {
}) })
.create(); .create();
assertEquals("{\"b\":2}", gson.toJson(new LocalRecord(1, 2, 3.0))); assertThat(gson.toJson(new LocalRecord(1, 2, 3.0))).isEqualTo("{\"b\":2}");
} }
@Test @Test
@ -365,8 +362,8 @@ public final class Java17RecordTest {
@JsonAdapter(Adapter.class) String s @JsonAdapter(Adapter.class) String s
) {} ) {}
assertEquals("{\"s\":\"serializer-a\"}", gson.toJson(new LocalRecord("a"))); assertThat(gson.toJson(new LocalRecord("a"))).isEqualTo("{\"s\":\"serializer-a\"}");
assertEquals(new LocalRecord("deserializer-a"), gson.fromJson("{\"s\":\"a\"}", LocalRecord.class)); assertThat(gson.fromJson("{\"s\":\"a\"}", LocalRecord.class)).isEqualTo(new LocalRecord("deserializer-a"));
} }
@Test @Test
@ -379,12 +376,12 @@ public final class Java17RecordTest {
.create(); .create();
String json = gson.toJson(new Allowed(1)); String json = gson.toJson(new Allowed(1));
assertEquals("{\"a\":1}", json); assertThat(json).isEqualTo("{\"a\":1}");
var exception = assertThrows(JsonIOException.class, () -> gson.toJson(new Blocked(1))); var exception = assertThrows(JsonIOException.class, () -> gson.toJson(new Blocked(1)));
assertEquals("ReflectionAccessFilter does not permit using reflection for class " + Blocked.class.getName() + assertThat(exception).hasMessageThat()
". Register a TypeAdapter for this type or adjust the access filter.", .isEqualTo("ReflectionAccessFilter does not permit using reflection for class " + Blocked.class.getName() +
exception.getMessage()); ". Register a TypeAdapter for this type or adjust the access filter.");
} }
@Test @Test
@ -394,19 +391,19 @@ public final class Java17RecordTest {
.create(); .create();
var exception = assertThrows(JsonIOException.class, () -> gson.toJson(new PrivateRecord(1))); var exception = assertThrows(JsonIOException.class, () -> gson.toJson(new PrivateRecord(1)));
assertEquals("Constructor 'com.google.gson.functional.Java17RecordTest$PrivateRecord(int)' is not accessible and" assertThat(exception).hasMessageThat()
.isEqualTo("Constructor 'com.google.gson.functional.Java17RecordTest$PrivateRecord(int)' is not accessible and"
+ " ReflectionAccessFilter does not permit making it accessible. Register a TypeAdapter for the declaring" + " 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.", + " type, adjust the access filter or increase the visibility of the element and its declaring type.");
exception.getMessage());
exception = assertThrows(JsonIOException.class, () -> gson.fromJson("{}", PrivateRecord.class)); exception = assertThrows(JsonIOException.class, () -> gson.fromJson("{}", PrivateRecord.class));
assertEquals("Constructor 'com.google.gson.functional.Java17RecordTest$PrivateRecord(int)' is not accessible and" assertThat(exception).hasMessageThat()
.isEqualTo("Constructor 'com.google.gson.functional.Java17RecordTest$PrivateRecord(int)' is not accessible and"
+ " ReflectionAccessFilter does not permit making it accessible. Register a TypeAdapter for the declaring" + " 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.", + " type, adjust the access filter or increase the visibility of the element and its declaring type.");
exception.getMessage());
assertEquals("{\"i\":1}", gson.toJson(new PublicRecord(1))); assertThat(gson.toJson(new PublicRecord(1))).isEqualTo("{\"i\":1}");
assertEquals(new PublicRecord(2), gson.fromJson("{\"i\":2}", PublicRecord.class)); assertThat(gson.fromJson("{\"i\":2}", PublicRecord.class)).isEqualTo(new PublicRecord(2));
} }
private record PrivateRecord(int i) {} private record PrivateRecord(int i) {}
@ -420,11 +417,11 @@ public final class Java17RecordTest {
public void testRecordBaseClass() { public void testRecordBaseClass() {
record LocalRecord(int i) {} record LocalRecord(int i) {}
assertEquals("{}", gson.toJson(new LocalRecord(1), Record.class)); assertThat(gson.toJson(new LocalRecord(1), Record.class)).isEqualTo("{}");
var exception = assertThrows(JsonIOException.class, () -> gson.fromJson("{}", Record.class)); var exception = assertThrows(JsonIOException.class, () -> gson.fromJson("{}", Record.class));
assertEquals("Abstract classes can't be instantiated! Register an InstanceCreator or a TypeAdapter for" assertThat(exception).hasMessageThat()
+ " this type. Class name: java.lang.Record", .isEqualTo("Abstract classes can't be instantiated! Register an InstanceCreator or a TypeAdapter for"
exception.getMessage()); + " this type. Class name: java.lang.Record");
} }
} }

View File

@ -16,8 +16,7 @@
package com.google.gson.functional; package com.google.gson.functional;
import static org.junit.Assert.assertEquals; import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertTrue;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;
@ -42,74 +41,74 @@ public class JavaUtilConcurrentAtomicTest {
} }
@Test @Test
public void testAtomicBoolean() throws Exception { public void testAtomicBoolean() {
AtomicBoolean target = gson.fromJson("true", AtomicBoolean.class); AtomicBoolean target = gson.fromJson("true", AtomicBoolean.class);
assertTrue(target.get()); assertThat(target.get()).isTrue();
String json = gson.toJson(target); String json = gson.toJson(target);
assertEquals("true", json); assertThat(json).isEqualTo("true");
} }
@Test @Test
public void testAtomicInteger() throws Exception { public void testAtomicInteger() {
AtomicInteger target = gson.fromJson("10", AtomicInteger.class); AtomicInteger target = gson.fromJson("10", AtomicInteger.class);
assertEquals(10, target.get()); assertThat(target.get()).isEqualTo(10);
String json = gson.toJson(target); String json = gson.toJson(target);
assertEquals("10", json); assertThat(json).isEqualTo("10");
} }
@Test @Test
public void testAtomicLong() throws Exception { public void testAtomicLong() {
AtomicLong target = gson.fromJson("10", AtomicLong.class); AtomicLong target = gson.fromJson("10", AtomicLong.class);
assertEquals(10, target.get()); assertThat(target.get()).isEqualTo(10);
String json = gson.toJson(target); String json = gson.toJson(target);
assertEquals("10", json); assertThat(json).isEqualTo("10");
} }
@Test @Test
public void testAtomicLongWithStringSerializationPolicy() throws Exception { public void testAtomicLongWithStringSerializationPolicy() {
Gson gson = new GsonBuilder() Gson gson = new GsonBuilder()
.setLongSerializationPolicy(LongSerializationPolicy.STRING) .setLongSerializationPolicy(LongSerializationPolicy.STRING)
.create(); .create();
AtomicLongHolder target = gson.fromJson("{'value':'10'}", AtomicLongHolder.class); AtomicLongHolder target = gson.fromJson("{'value':'10'}", AtomicLongHolder.class);
assertEquals(10, target.value.get()); assertThat(target.value.get()).isEqualTo(10);
String json = gson.toJson(target); String json = gson.toJson(target);
assertEquals("{\"value\":\"10\"}", json); assertThat(json).isEqualTo("{\"value\":\"10\"}");
} }
@Test @Test
public void testAtomicIntegerArray() throws Exception { public void testAtomicIntegerArray() {
AtomicIntegerArray target = gson.fromJson("[10, 13, 14]", AtomicIntegerArray.class); AtomicIntegerArray target = gson.fromJson("[10, 13, 14]", AtomicIntegerArray.class);
assertEquals(3, target.length()); assertThat(target.length()).isEqualTo(3);
assertEquals(10, target.get(0)); assertThat(target.get(0)).isEqualTo(10);
assertEquals(13, target.get(1)); assertThat(target.get(1)).isEqualTo(13);
assertEquals(14, target.get(2)); assertThat(target.get(2)).isEqualTo(14);
String json = gson.toJson(target); String json = gson.toJson(target);
assertEquals("[10,13,14]", json); assertThat(json).isEqualTo("[10,13,14]");
} }
@Test @Test
public void testAtomicLongArray() throws Exception { public void testAtomicLongArray() {
AtomicLongArray target = gson.fromJson("[10, 13, 14]", AtomicLongArray.class); AtomicLongArray target = gson.fromJson("[10, 13, 14]", AtomicLongArray.class);
assertEquals(3, target.length()); assertThat(target.length()).isEqualTo(3);
assertEquals(10, target.get(0)); assertThat(target.get(0)).isEqualTo(10);
assertEquals(13, target.get(1)); assertThat(target.get(1)).isEqualTo(13);
assertEquals(14, target.get(2)); assertThat(target.get(2)).isEqualTo(14);
String json = gson.toJson(target); String json = gson.toJson(target);
assertEquals("[10,13,14]", json); assertThat(json).isEqualTo("[10,13,14]");
} }
@Test @Test
public void testAtomicLongArrayWithStringSerializationPolicy() throws Exception { public void testAtomicLongArrayWithStringSerializationPolicy() {
Gson gson = new GsonBuilder() Gson gson = new GsonBuilder()
.setLongSerializationPolicy(LongSerializationPolicy.STRING) .setLongSerializationPolicy(LongSerializationPolicy.STRING)
.create(); .create();
AtomicLongArray target = gson.fromJson("['10', '13', '14']", AtomicLongArray.class); AtomicLongArray target = gson.fromJson("['10', '13', '14']", AtomicLongArray.class);
assertEquals(3, target.length()); assertThat(target.length()).isEqualTo(3);
assertEquals(10, target.get(0)); assertThat(target.get(0)).isEqualTo(10);
assertEquals(13, target.get(1)); assertThat(target.get(1)).isEqualTo(13);
assertEquals(14, target.get(2)); assertThat(target.get(2)).isEqualTo(14);
String json = gson.toJson(target); String json = gson.toJson(target);
assertEquals("[\"10\",\"13\",\"14\"]", json); assertThat(json).isEqualTo("[\"10\",\"13\",\"14\"]");
} }
private static class AtomicLongHolder { private static class AtomicLongHolder {

View File

@ -16,9 +16,7 @@
package com.google.gson.functional; package com.google.gson.functional;
import static org.junit.Assert.assertEquals; import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import com.google.gson.Gson; import com.google.gson.Gson;
import java.util.Currency; import java.util.Currency;
@ -38,16 +36,16 @@ public class JavaUtilTest {
} }
@Test @Test
public void testCurrency() throws Exception { public void testCurrency() {
CurrencyHolder target = gson.fromJson("{'value':'USD'}", CurrencyHolder.class); CurrencyHolder target = gson.fromJson("{'value':'USD'}", CurrencyHolder.class);
assertEquals("USD", target.value.getCurrencyCode()); assertThat(target.value.getCurrencyCode()).isEqualTo("USD");
String json = gson.toJson(target); String json = gson.toJson(target);
assertEquals("{\"value\":\"USD\"}", json); assertThat(json).isEqualTo("{\"value\":\"USD\"}");
// null handling // null handling
target = gson.fromJson("{'value':null}", CurrencyHolder.class); target = gson.fromJson("{'value':null}", CurrencyHolder.class);
assertNull(target.value); assertThat(target.value).isNull();
assertEquals("{}", gson.toJson(target)); assertThat(gson.toJson(target)).isEqualTo("{}");
} }
private static class CurrencyHolder { private static class CurrencyHolder {
@ -57,10 +55,10 @@ public class JavaUtilTest {
@Test @Test
public void testProperties() { public void testProperties() {
Properties props = gson.fromJson("{'a':'v1','b':'v2'}", Properties.class); Properties props = gson.fromJson("{'a':'v1','b':'v2'}", Properties.class);
assertEquals("v1", props.getProperty("a")); assertThat(props.getProperty("a")).isEqualTo("v1");
assertEquals("v2", props.getProperty("b")); assertThat(props.getProperty("b")).isEqualTo("v2");
String json = gson.toJson(props); String json = gson.toJson(props);
assertTrue(json.contains("\"a\":\"v1\"")); assertThat(json).contains("\"a\":\"v1\"");
assertTrue(json.contains("\"b\":\"v2\"")); assertThat(json).contains("\"b\":\"v2\"");
} }
} }

View File

@ -16,9 +16,7 @@
package com.google.gson.functional; package com.google.gson.functional;
import static org.junit.Assert.assertEquals; import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import com.google.gson.Gson; import com.google.gson.Gson;
@ -50,28 +48,28 @@ public final class JsonAdapterAnnotationOnClassesTest {
public void testJsonAdapterInvoked() { public void testJsonAdapterInvoked() {
Gson gson = new Gson(); Gson gson = new Gson();
String json = gson.toJson(new A("bar")); String json = gson.toJson(new A("bar"));
assertEquals("\"jsonAdapter\"", json); assertThat(json).isEqualTo("\"jsonAdapter\"");
// Also invoke the JsonAdapter javadoc sample // Also invoke the JsonAdapter javadoc sample
json = gson.toJson(new User("Inderjeet", "Singh")); json = gson.toJson(new User("Inderjeet", "Singh"));
assertEquals("{\"name\":\"Inderjeet Singh\"}", json); assertThat(json).isEqualTo("{\"name\":\"Inderjeet Singh\"}");
User user = gson.fromJson("{'name':'Joel Leitch'}", User.class); User user = gson.fromJson("{'name':'Joel Leitch'}", User.class);
assertEquals("Joel", user.firstName); assertThat(user.firstName).isEqualTo("Joel");
assertEquals("Leitch", user.lastName); assertThat(user.lastName).isEqualTo("Leitch");
json = gson.toJson(Foo.BAR); json = gson.toJson(Foo.BAR);
assertEquals("\"bar\"", json); assertThat(json).isEqualTo("\"bar\"");
Foo baz = gson.fromJson("\"baz\"", Foo.class); Foo baz = gson.fromJson("\"baz\"", Foo.class);
assertEquals(Foo.BAZ, baz); assertThat(baz).isEqualTo(Foo.BAZ);
} }
@Test @Test
public void testJsonAdapterFactoryInvoked() { public void testJsonAdapterFactoryInvoked() {
Gson gson = new Gson(); Gson gson = new Gson();
String json = gson.toJson(new C("bar")); String json = gson.toJson(new C("bar"));
assertEquals("\"jsonAdapterFactory\"", json); assertThat(json).isEqualTo("\"jsonAdapterFactory\"");
C c = gson.fromJson("\"bar\"", C.class); C c = gson.fromJson("\"bar\"", C.class);
assertEquals("jsonAdapterFactory", c.value); assertThat(c.value).isEqualTo("jsonAdapterFactory");
} }
@Test @Test
@ -88,7 +86,7 @@ public final class JsonAdapterAnnotationOnClassesTest {
.registerTypeAdapter(A.class, typeAdapter) .registerTypeAdapter(A.class, typeAdapter)
.create(); .create();
String json = gson.toJson(new A("abcd")); String json = gson.toJson(new A("abcd"));
assertEquals("\"registeredAdapter\"", json); assertThat(json).isEqualTo("\"registeredAdapter\"");
} }
/** /**
@ -106,9 +104,9 @@ public final class JsonAdapterAnnotationOnClassesTest {
.registerTypeAdapter(A.class, serializer) .registerTypeAdapter(A.class, serializer)
.create(); .create();
String json = gson.toJson(new A("abcd")); String json = gson.toJson(new A("abcd"));
assertEquals("\"registeredSerializer\"", json); assertThat(json).isEqualTo("\"registeredSerializer\"");
A target = gson.fromJson("abcd", A.class); A target = gson.fromJson("abcd", A.class);
assertEquals("jsonAdapter", target.value); assertThat(target.value).isEqualTo("jsonAdapter");
} }
/** /**
@ -126,9 +124,9 @@ public final class JsonAdapterAnnotationOnClassesTest {
.registerTypeAdapter(A.class, deserializer) .registerTypeAdapter(A.class, deserializer)
.create(); .create();
String json = gson.toJson(new A("abcd")); String json = gson.toJson(new A("abcd"));
assertEquals("\"jsonAdapter\"", json); assertThat(json).isEqualTo("\"jsonAdapter\"");
A target = gson.fromJson("abcd", A.class); A target = gson.fromJson("abcd", A.class);
assertEquals("registeredDeserializer", target.value); assertThat(target.value).isEqualTo("registeredDeserializer");
} }
@Test @Test
@ -142,14 +140,14 @@ public final class JsonAdapterAnnotationOnClassesTest {
@Test @Test
public void testSuperclassTypeAdapterNotInvoked() { public void testSuperclassTypeAdapterNotInvoked() {
String json = new Gson().toJson(new B("bar")); String json = new Gson().toJson(new B("bar"));
assertFalse(json.contains("jsonAdapter")); assertThat(json).doesNotContain("jsonAdapter");
} }
@Test @Test
public void testNullSafeObjectFromJson() { public void testNullSafeObjectFromJson() {
Gson gson = new Gson(); Gson gson = new Gson();
NullableClass fromJson = gson.fromJson("null", NullableClass.class); NullableClass fromJson = gson.fromJson("null", NullableClass.class);
assertNull(fromJson); assertThat(fromJson).isNull();
} }
@JsonAdapter(A.JsonAdapter.class) @JsonAdapter(A.JsonAdapter.class)

View File

@ -16,9 +16,7 @@
package com.google.gson.functional; package com.google.gson.functional;
import static org.junit.Assert.assertEquals; import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;
@ -41,18 +39,18 @@ public final class JsonAdapterAnnotationOnFieldsTest {
public void testClassAnnotationAdapterTakesPrecedenceOverDefault() { public void testClassAnnotationAdapterTakesPrecedenceOverDefault() {
Gson gson = new Gson(); Gson gson = new Gson();
String json = gson.toJson(new Computer(new User("Inderjeet Singh"))); String json = gson.toJson(new Computer(new User("Inderjeet Singh")));
assertEquals("{\"user\":\"UserClassAnnotationAdapter\"}", json); assertThat(json).isEqualTo("{\"user\":\"UserClassAnnotationAdapter\"}");
Computer computer = gson.fromJson("{'user':'Inderjeet Singh'}", Computer.class); Computer computer = gson.fromJson("{'user':'Inderjeet Singh'}", Computer.class);
assertEquals("UserClassAnnotationAdapter", computer.user.name); assertThat(computer.user.name).isEqualTo("UserClassAnnotationAdapter");
} }
@Test @Test
public void testClassAnnotationAdapterFactoryTakesPrecedenceOverDefault() { public void testClassAnnotationAdapterFactoryTakesPrecedenceOverDefault() {
Gson gson = new Gson(); Gson gson = new Gson();
String json = gson.toJson(new Gizmo(new Part("Part"))); String json = gson.toJson(new Gizmo(new Part("Part")));
assertEquals("{\"part\":\"GizmoPartTypeAdapterFactory\"}", json); assertThat(json).isEqualTo("{\"part\":\"GizmoPartTypeAdapterFactory\"}");
Gizmo computer = gson.fromJson("{'part':'Part'}", Gizmo.class); Gizmo computer = gson.fromJson("{'part':'Part'}", Gizmo.class);
assertEquals("GizmoPartTypeAdapterFactory", computer.part.name); assertThat(computer.part.name).isEqualTo("GizmoPartTypeAdapterFactory");
} }
@Test @Test
@ -61,35 +59,35 @@ public final class JsonAdapterAnnotationOnFieldsTest {
.registerTypeAdapter(User.class, new RegisteredUserAdapter()) .registerTypeAdapter(User.class, new RegisteredUserAdapter())
.create(); .create();
String json = gson.toJson(new Computer(new User("Inderjeet Singh"))); String json = gson.toJson(new Computer(new User("Inderjeet Singh")));
assertEquals("{\"user\":\"RegisteredUserAdapter\"}", json); assertThat(json).isEqualTo("{\"user\":\"RegisteredUserAdapter\"}");
Computer computer = gson.fromJson("{'user':'Inderjeet Singh'}", Computer.class); Computer computer = gson.fromJson("{'user':'Inderjeet Singh'}", Computer.class);
assertEquals("RegisteredUserAdapter", computer.user.name); assertThat(computer.user.name).isEqualTo("RegisteredUserAdapter");
} }
@Test @Test
public void testFieldAnnotationTakesPrecedenceOverRegisteredTypeAdapter() { public void testFieldAnnotationTakesPrecedenceOverRegisteredTypeAdapter() {
Gson gson = new GsonBuilder() Gson gson = new GsonBuilder()
.registerTypeAdapter(Part.class, new TypeAdapter<Part>() { .registerTypeAdapter(Part.class, new TypeAdapter<Part>() {
@Override public void write(JsonWriter out, Part part) throws IOException { @Override public void write(JsonWriter out, Part part) {
throw new AssertionError(); throw new AssertionError();
} }
@Override public Part read(JsonReader in) throws IOException { @Override public Part read(JsonReader in) {
throw new AssertionError(); throw new AssertionError();
} }
}).create(); }).create();
String json = gson.toJson(new Gadget(new Part("screen"))); String json = gson.toJson(new Gadget(new Part("screen")));
assertEquals("{\"part\":\"PartJsonFieldAnnotationAdapter\"}", json); assertThat(json).isEqualTo("{\"part\":\"PartJsonFieldAnnotationAdapter\"}");
Gadget gadget = gson.fromJson("{'part':'screen'}", Gadget.class); Gadget gadget = gson.fromJson("{'part':'screen'}", Gadget.class);
assertEquals("PartJsonFieldAnnotationAdapter", gadget.part.name); assertThat(gadget.part.name).isEqualTo("PartJsonFieldAnnotationAdapter");
} }
@Test @Test
public void testFieldAnnotationTakesPrecedenceOverClassAnnotation() { public void testFieldAnnotationTakesPrecedenceOverClassAnnotation() {
Gson gson = new Gson(); Gson gson = new Gson();
String json = gson.toJson(new Computer2(new User("Inderjeet Singh"))); String json = gson.toJson(new Computer2(new User("Inderjeet Singh")));
assertEquals("{\"user\":\"UserFieldAnnotationAdapter\"}", json); assertThat(json).isEqualTo("{\"user\":\"UserFieldAnnotationAdapter\"}");
Computer2 target = gson.fromJson("{'user':'Interjeet Singh'}", Computer2.class); Computer2 target = gson.fromJson("{'user':'Interjeet Singh'}", Computer2.class);
assertEquals("UserFieldAnnotationAdapter", target.user.name); assertThat(target.user.name).isEqualTo("UserFieldAnnotationAdapter");
} }
private static final class Gadget { private static final class Gadget {
@ -199,8 +197,8 @@ public final class JsonAdapterAnnotationOnFieldsTest {
Gson gson = new Gson(); Gson gson = new Gson();
String json = "{'part1':'name','part2':{'name':'name2'}}"; String json = "{'part1':'name','part2':{'name':'name2'}}";
GadgetWithTwoParts gadget = gson.fromJson(json, GadgetWithTwoParts.class); GadgetWithTwoParts gadget = gson.fromJson(json, GadgetWithTwoParts.class);
assertEquals("PartJsonFieldAnnotationAdapter", gadget.part1.name); assertThat(gadget.part1.name).isEqualTo("PartJsonFieldAnnotationAdapter");
assertEquals("name2", gadget.part2.name); assertThat(gadget.part2.name).isEqualTo("name2");
} }
private static final class GadgetWithTwoParts { private static final class GadgetWithTwoParts {
@ -218,10 +216,10 @@ public final class JsonAdapterAnnotationOnFieldsTest {
String fromJson = "{'part':null}"; String fromJson = "{'part':null}";
GadgetWithOptionalPart gadget = gson.fromJson(fromJson, GadgetWithOptionalPart.class); GadgetWithOptionalPart gadget = gson.fromJson(fromJson, GadgetWithOptionalPart.class);
assertNull(gadget.part); assertThat(gadget.part).isNull();
String toJson = gson.toJson(gadget); String toJson = gson.toJson(gadget);
assertFalse(toJson.contains("PartJsonFieldAnnotationAdapter")); assertThat(toJson).doesNotContain("PartJsonFieldAnnotationAdapter");
} }
private static final class GadgetWithOptionalPart { private static final class GadgetWithOptionalPart {
@ -238,9 +236,9 @@ public final class JsonAdapterAnnotationOnFieldsTest {
public void testNonPrimitiveFieldAnnotationTakesPrecedenceOverDefault() { public void testNonPrimitiveFieldAnnotationTakesPrecedenceOverDefault() {
Gson gson = new Gson(); Gson gson = new Gson();
String json = gson.toJson(new GadgetWithOptionalPart(new Part("foo"))); String json = gson.toJson(new GadgetWithOptionalPart(new Part("foo")));
assertEquals("{\"part\":\"PartJsonFieldAnnotationAdapter\"}", json); assertThat(json).isEqualTo("{\"part\":\"PartJsonFieldAnnotationAdapter\"}");
GadgetWithOptionalPart gadget = gson.fromJson("{'part':'foo'}", GadgetWithOptionalPart.class); GadgetWithOptionalPart gadget = gson.fromJson("{'part':'foo'}", GadgetWithOptionalPart.class);
assertEquals("PartJsonFieldAnnotationAdapter", gadget.part.name); assertThat(gadget.part.name).isEqualTo("PartJsonFieldAnnotationAdapter");
} }
/** Regression test contributed through https://github.com/google/gson/issues/831 */ /** Regression test contributed through https://github.com/google/gson/issues/831 */
@ -248,9 +246,9 @@ public final class JsonAdapterAnnotationOnFieldsTest {
public void testPrimitiveFieldAnnotationTakesPrecedenceOverDefault() { public void testPrimitiveFieldAnnotationTakesPrecedenceOverDefault() {
Gson gson = new Gson(); Gson gson = new Gson();
String json = gson.toJson(new GadgetWithPrimitivePart(42)); String json = gson.toJson(new GadgetWithPrimitivePart(42));
assertEquals("{\"part\":\"42\"}", json); assertThat(json).isEqualTo("{\"part\":\"42\"}");
GadgetWithPrimitivePart gadget = gson.fromJson(json, GadgetWithPrimitivePart.class); GadgetWithPrimitivePart gadget = gson.fromJson(json, GadgetWithPrimitivePart.class);
assertEquals(42, gadget.part); assertThat(gadget.part).isEqualTo(42);
} }
private static final class GadgetWithPrimitivePart { private static final class GadgetWithPrimitivePart {
@ -288,9 +286,9 @@ public final class JsonAdapterAnnotationOnFieldsTest {
public void testFieldAnnotationWorksForParameterizedType() { public void testFieldAnnotationWorksForParameterizedType() {
Gson gson = new Gson(); Gson gson = new Gson();
String json = gson.toJson(new Gizmo2(Arrays.asList(new Part("Part")))); String json = gson.toJson(new Gizmo2(Arrays.asList(new Part("Part"))));
assertEquals("{\"part\":\"GizmoPartTypeAdapterFactory\"}", json); assertThat(json).isEqualTo("{\"part\":\"GizmoPartTypeAdapterFactory\"}");
Gizmo2 computer = gson.fromJson("{'part':'Part'}", Gizmo2.class); Gizmo2 computer = gson.fromJson("{'part':'Part'}", Gizmo2.class);
assertEquals("GizmoPartTypeAdapterFactory", computer.part.get(0).name); assertThat(computer.part.get(0).name).isEqualTo("GizmoPartTypeAdapterFactory");
} }
private static final class Gizmo2 { private static final class Gizmo2 {

View File

@ -16,9 +16,7 @@
package com.google.gson.functional; package com.google.gson.functional;
import static org.junit.Assert.assertEquals; import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializationContext;
@ -42,10 +40,10 @@ public final class JsonAdapterSerializerDeserializerTest {
public void testJsonSerializerDeserializerBasedJsonAdapterOnFields() { public void testJsonSerializerDeserializerBasedJsonAdapterOnFields() {
Gson gson = new Gson(); Gson gson = new Gson();
String json = gson.toJson(new Computer(new User("Inderjeet Singh"), null, new User("Jesse Wilson"))); String json = gson.toJson(new Computer(new User("Inderjeet Singh"), null, new User("Jesse Wilson")));
assertEquals("{\"user1\":\"UserSerializer\",\"user3\":\"UserSerializerDeserializer\"}", json); assertThat(json).isEqualTo("{\"user1\":\"UserSerializer\",\"user3\":\"UserSerializerDeserializer\"}");
Computer computer = gson.fromJson("{'user2':'Jesse Wilson','user3':'Jake Wharton'}", Computer.class); Computer computer = gson.fromJson("{'user2':'Jesse Wilson','user3':'Jake Wharton'}", Computer.class);
assertEquals("UserSerializer", computer.user2.name); assertThat(computer.user2.name).isEqualTo("UserSerializer");
assertEquals("UserSerializerDeserializer", computer.user3.name); assertThat(computer.user3.name).isEqualTo("UserSerializerDeserializer");
} }
private static final class Computer { private static final class Computer {
@ -97,9 +95,9 @@ public final class JsonAdapterSerializerDeserializerTest {
public void testJsonSerializerDeserializerBasedJsonAdapterOnClass() { public void testJsonSerializerDeserializerBasedJsonAdapterOnClass() {
Gson gson = new Gson(); Gson gson = new Gson();
String json = gson.toJson(new Computer2(new User2("Inderjeet Singh"))); String json = gson.toJson(new Computer2(new User2("Inderjeet Singh")));
assertEquals("{\"user\":\"UserSerializerDeserializer2\"}", json); assertThat(json).isEqualTo("{\"user\":\"UserSerializerDeserializer2\"}");
Computer2 computer = gson.fromJson("{'user':'Inderjeet Singh'}", Computer2.class); Computer2 computer = gson.fromJson("{'user':'Inderjeet Singh'}", Computer2.class);
assertEquals("UserSerializerDeserializer2", computer.user.name); assertThat(computer.user.name).isEqualTo("UserSerializerDeserializer2");
} }
private static final class Computer2 { private static final class Computer2 {
@ -134,8 +132,8 @@ public final class JsonAdapterSerializerDeserializerTest {
Container c = new Container("Foo", 10); Container c = new Container("Foo", 10);
Gson gson = new Gson(); Gson gson = new Gson();
String json = gson.toJson(c); String json = gson.toJson(c);
assertTrue(json.contains("\"a\":\"BaseStringAdapter\"")); assertThat(json).contains("\"a\":\"BaseStringAdapter\"");
assertTrue(json.contains("\"b\":\"BaseIntegerAdapter\"")); assertThat(json).contains("\"b\":\"BaseIntegerAdapter\"");
} }
private static final class Container { private static final class Container {
@ -171,10 +169,10 @@ public final class JsonAdapterSerializerDeserializerTest {
public void testJsonAdapterNullSafe() { public void testJsonAdapterNullSafe() {
Gson gson = new Gson(); Gson gson = new Gson();
String json = gson.toJson(new Computer3(null, null)); String json = gson.toJson(new Computer3(null, null));
assertEquals("{\"user1\":\"UserSerializerDeserializer\"}", json); assertThat(json).isEqualTo("{\"user1\":\"UserSerializerDeserializer\"}");
Computer3 computer3 = gson.fromJson("{\"user1\":null, \"user2\":null}", Computer3.class); Computer3 computer3 = gson.fromJson("{\"user1\":null, \"user2\":null}", Computer3.class);
assertEquals("UserSerializerDeserializer", computer3.user1.name); assertThat(computer3.user1.name).isEqualTo("UserSerializerDeserializer");
assertNull(computer3.user2); assertThat(computer3.user2).isNull();
} }
private static final class Computer3 { private static final class Computer3 {

View File

@ -16,7 +16,7 @@
package com.google.gson.functional; 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.Assert.fail;
import com.google.gson.Gson; import com.google.gson.Gson;
@ -65,8 +65,8 @@ public class JsonParserTest {
obj.addProperty("stringValue", "foo"); obj.addProperty("stringValue", "foo");
obj.addProperty("intValue", 11); obj.addProperty("intValue", 11);
BagOfPrimitives target = gson.fromJson(obj, BagOfPrimitives.class); BagOfPrimitives target = gson.fromJson(obj, BagOfPrimitives.class);
assertEquals(11, target.intValue); assertThat(target.intValue).isEqualTo(11);
assertEquals("foo", target.stringValue); assertThat(target.stringValue).isEqualTo("foo");
} }
@Test @Test
@ -123,17 +123,17 @@ public class JsonParserTest {
obj.remove("stringValue"); obj.remove("stringValue");
obj.addProperty("stringValue", "fooBar"); obj.addProperty("stringValue", "fooBar");
BagOfPrimitives target = gson.fromJson(obj, BagOfPrimitives.class); BagOfPrimitives target = gson.fromJson(obj, BagOfPrimitives.class);
assertEquals(10, target.intValue); assertThat(target.intValue).isEqualTo(10);
assertEquals(20, target.longValue); assertThat(target.longValue).isEqualTo(20);
assertEquals("fooBar", target.stringValue); assertThat(target.stringValue).isEqualTo("fooBar");
} }
@Test @Test
public void testExtraCommasInArrays() { public void testExtraCommasInArrays() {
Type type = new TypeToken<List<String>>() {}.getType(); Type type = new TypeToken<List<String>>() {}.getType();
assertEquals(Arrays.asList("a", null, "b", null, null), gson.fromJson("[a,,b,,]", type)); assertThat(Arrays.asList("a", null, "b", null, null)).isEqualTo(gson.fromJson("[a,,b,,]", type));
assertEquals(Arrays.asList(null, null), gson.fromJson("[,]", type)); assertThat(Arrays.asList(null, null)).isEqualTo(gson.fromJson("[,]", type));
assertEquals(Arrays.asList("a", null), gson.fromJson("[a,]", type)); assertThat(Arrays.asList("a", null)).isEqualTo(gson.fromJson("[a,]", type));
} }
@Test @Test

View File

@ -1,8 +1,6 @@
package com.google.gson.functional; package com.google.gson.functional;
import static org.junit.Assert.assertEquals; import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import com.google.gson.Gson; import com.google.gson.Gson;
@ -35,10 +33,10 @@ public class JsonTreeTest {
public void testToJsonTree() { public void testToJsonTree() {
BagOfPrimitives bag = new BagOfPrimitives(10L, 5, false, "foo"); BagOfPrimitives bag = new BagOfPrimitives(10L, 5, false, "foo");
JsonElement json = gson.toJsonTree(bag); JsonElement json = gson.toJsonTree(bag);
assertTrue(json.isJsonObject()); assertThat(json.isJsonObject()).isTrue();
JsonObject obj = json.getAsJsonObject(); JsonObject obj = json.getAsJsonObject();
Set<Entry<String, JsonElement>> children = obj.entrySet(); Set<Entry<String, JsonElement>> children = obj.entrySet();
assertEquals(4, children.size()); assertThat(children).hasSize(4);
assertContains(obj, new JsonPrimitive(10L)); assertContains(obj, new JsonPrimitive(10L));
assertContains(obj, new JsonPrimitive(5)); assertContains(obj, new JsonPrimitive(5));
assertContains(obj, new JsonPrimitive(false)); assertContains(obj, new JsonPrimitive(false));
@ -49,10 +47,10 @@ public class JsonTreeTest {
public void testToJsonTreeObjectType() { public void testToJsonTreeObjectType() {
SubTypeOfBagOfPrimitives bag = new SubTypeOfBagOfPrimitives(10L, 5, false, "foo", 1.4F); SubTypeOfBagOfPrimitives bag = new SubTypeOfBagOfPrimitives(10L, 5, false, "foo", 1.4F);
JsonElement json = gson.toJsonTree(bag, BagOfPrimitives.class); JsonElement json = gson.toJsonTree(bag, BagOfPrimitives.class);
assertTrue(json.isJsonObject()); assertThat(json.isJsonObject()).isTrue();
JsonObject obj = json.getAsJsonObject(); JsonObject obj = json.getAsJsonObject();
Set<Entry<String, JsonElement>> children = obj.entrySet(); Set<Entry<String, JsonElement>> children = obj.entrySet();
assertEquals(4, children.size()); assertThat(children).hasSize(4);
assertContains(obj, new JsonPrimitive(10L)); assertContains(obj, new JsonPrimitive(10L));
assertContains(obj, new JsonPrimitive(5)); assertContains(obj, new JsonPrimitive(5));
assertContains(obj, new JsonPrimitive(false)); assertContains(obj, new JsonPrimitive(false));
@ -65,14 +63,14 @@ public class JsonTreeTest {
String json1 = gson.toJson(bag); String json1 = gson.toJson(bag);
JsonElement jsonElement = gson.toJsonTree(bag, SubTypeOfBagOfPrimitives.class); JsonElement jsonElement = gson.toJsonTree(bag, SubTypeOfBagOfPrimitives.class);
String json2 = gson.toJson(jsonElement); String json2 = gson.toJson(jsonElement);
assertEquals(json1, json2); assertThat(json2).isEqualTo(json1);
} }
@Test @Test
public void testJsonTreeNull() { public void testJsonTreeNull() {
BagOfPrimitives bag = new BagOfPrimitives(10L, 5, false, null); BagOfPrimitives bag = new BagOfPrimitives(10L, 5, false, null);
JsonObject jsonElement = (JsonObject) gson.toJsonTree(bag, BagOfPrimitives.class); JsonObject jsonElement = (JsonObject) gson.toJsonTree(bag, BagOfPrimitives.class);
assertFalse(jsonElement.has("stringValue")); assertThat(jsonElement.has("stringValue")).isFalse();
} }
private void assertContains(JsonObject json, JsonPrimitive child) { private void assertContains(JsonObject json, JsonPrimitive child) {

View File

@ -15,8 +15,8 @@
*/ */
package com.google.gson.functional; package com.google.gson.functional;
import static com.google.common.truth.Truth.assertThat;
import static java.util.Collections.singletonList; import static java.util.Collections.singletonList;
import static org.junit.Assert.assertEquals;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;
@ -43,6 +43,6 @@ public class LeniencyTest {
+ "[ # One!\n" + "[ # One!\n"
+ " 'Hi' #Element!\n" + " 'Hi' #Element!\n"
+ "] # Array!", new TypeToken<List<String>>() {}.getType()); + "] # Array!", new TypeToken<List<String>>() {}.getType());
assertEquals(singletonList("Hi"), json); assertThat(json).isEqualTo(singletonList("Hi"));
} }
} }

View File

@ -16,7 +16,7 @@
package com.google.gson.functional; 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.Assert.fail;
import com.google.gson.Gson; import com.google.gson.Gson;
@ -43,19 +43,18 @@ public class MapAsArrayTypeAdapterTest {
original.put(new Point(5, 5), "a"); original.put(new Point(5, 5), "a");
original.put(new Point(8, 8), "b"); original.put(new Point(8, 8), "b");
String json = gson.toJson(original, type); String json = gson.toJson(original, type);
assertEquals("[[{\"x\":5,\"y\":5},\"a\"],[{\"x\":8,\"y\":8},\"b\"]]", json); assertThat(json).isEqualTo("[[{\"x\":5,\"y\":5},\"a\"],[{\"x\":8,\"y\":8},\"b\"]]");
assertEquals(original, gson.<Map<Point, String>>fromJson(json, type)); assertThat(gson.<Map<Point, String>>fromJson(json, type)).isEqualTo(original);
// test that registering a type adapter for one map doesn't interfere with others // test that registering a type adapter for one map doesn't interfere with others
Map<String, Boolean> otherMap = new LinkedHashMap<>(); Map<String, Boolean> otherMap = new LinkedHashMap<>();
otherMap.put("t", true); otherMap.put("t", true);
otherMap.put("f", false); otherMap.put("f", false);
assertEquals("{\"t\":true,\"f\":false}", assertThat(gson.toJson(otherMap, Map.class)).isEqualTo("{\"t\":true,\"f\":false}");
gson.toJson(otherMap, Map.class)); assertThat(gson.toJson(otherMap, new TypeToken<Map<String, Boolean>>() {}.getType()))
assertEquals("{\"t\":true,\"f\":false}", .isEqualTo("{\"t\":true,\"f\":false}");
gson.toJson(otherMap, new TypeToken<Map<String, Boolean>>() {}.getType())); assertThat(gson.<Object>fromJson("{\"t\":true,\"f\":false}", new TypeToken<Map<String, Boolean>>() {}.getType()))
assertEquals(otherMap, gson.<Object>fromJson("{\"t\":true,\"f\":false}", .isEqualTo(otherMap);
new TypeToken<Map<String, Boolean>>() {}.getType()));
} }
@Test @Test
@ -90,7 +89,7 @@ public class MapAsArrayTypeAdapterTest {
} }
@Test @Test
public void testMultipleEnableComplexKeyRegistrationHasNoEffect() throws Exception { public void testMultipleEnableComplexKeyRegistrationHasNoEffect() {
Type type = new TypeToken<Map<Point, String>>() {}.getType(); Type type = new TypeToken<Map<Point, String>>() {}.getType();
Gson gson = new GsonBuilder() Gson gson = new GsonBuilder()
.enableComplexMapKeySerialization() .enableComplexMapKeySerialization()
@ -101,8 +100,8 @@ public class MapAsArrayTypeAdapterTest {
original.put(new Point(6, 5), "abc"); original.put(new Point(6, 5), "abc");
original.put(new Point(1, 8), "def"); original.put(new Point(1, 8), "def");
String json = gson.toJson(original, type); String json = gson.toJson(original, type);
assertEquals("[[{\"x\":6,\"y\":5},\"abc\"],[{\"x\":1,\"y\":8},\"def\"]]", json); assertThat(json).isEqualTo("[[{\"x\":6,\"y\":5},\"abc\"],[{\"x\":1,\"y\":8},\"def\"]]");
assertEquals(original, gson.<Map<Point, String>>fromJson(json, type)); assertThat(gson.<Map<Point, String>>fromJson(json, type)).isEqualTo(original);
} }
@Test @Test
@ -112,7 +111,7 @@ public class MapAsArrayTypeAdapterTest {
map.map.put(new Point(2, 3), new Point(4, 5)); map.map.put(new Point(2, 3), new Point(4, 5));
Type type = new TypeToken<PointWithProperty<Point>>(){}.getType(); Type type = new TypeToken<PointWithProperty<Point>>(){}.getType();
String json = gson.toJson(map, type); String json = gson.toJson(map, type);
assertEquals("{\"map\":[[{\"x\":2,\"y\":3},{\"x\":4,\"y\":5}]]}", json); assertThat(json).isEqualTo("{\"map\":[[{\"x\":2,\"y\":3},{\"x\":4,\"y\":5}]]}");
} }
@Test @Test
@ -123,8 +122,8 @@ public class MapAsArrayTypeAdapterTest {
PointWithProperty<Point> map = gson.fromJson(json, type); PointWithProperty<Point> map = gson.fromJson(json, type);
Point key = map.map.keySet().iterator().next(); Point key = map.map.keySet().iterator().next();
Point value = map.map.values().iterator().next(); Point value = map.map.values().iterator().next();
assertEquals(new Point(2, 3), key); assertThat(key).isEqualTo(new Point(2, 3));
assertEquals(new Point(4, 5), value); assertThat(value).isEqualTo(new Point(4, 5));
} }
static class Point { static class Point {

View File

@ -16,10 +16,7 @@
package com.google.gson.functional; package com.google.gson.functional;
import static org.junit.Assert.assertEquals; import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import com.google.gson.Gson; import com.google.gson.Gson;
@ -71,8 +68,8 @@ public class MapTest {
map.put("b", 2); map.put("b", 2);
Type typeOfMap = new TypeToken<Map<String, Integer>>() {}.getType(); Type typeOfMap = new TypeToken<Map<String, Integer>>() {}.getType();
String json = gson.toJson(map, typeOfMap); String json = gson.toJson(map, typeOfMap);
assertTrue(json.contains("\"a\":1")); assertThat(json).contains("\"a\":1");
assertTrue(json.contains("\"b\":2")); assertThat(json).contains("\"b\":2");
} }
@Test @Test
@ -80,8 +77,8 @@ public class MapTest {
String json = "{\"a\":1,\"b\":2}"; String json = "{\"a\":1,\"b\":2}";
Type typeOfMap = new TypeToken<Map<String,Integer>>(){}.getType(); Type typeOfMap = new TypeToken<Map<String,Integer>>(){}.getType();
Map<String, Integer> target = gson.fromJson(json, typeOfMap); Map<String, Integer> target = gson.fromJson(json, typeOfMap);
assertEquals(1, target.get("a").intValue()); assertThat(target.get("a")).isEqualTo(1);
assertEquals(2, target.get("b").intValue()); assertThat(target.get("b")).isEqualTo(2);
} }
@Test @Test
@ -90,8 +87,8 @@ public class MapTest {
map.put("a", 1); map.put("a", 1);
map.put("b", "string"); map.put("b", "string");
String json = gson.toJson(map); String json = gson.toJson(map);
assertTrue(json.contains("\"a\":1")); assertThat(json).contains("\"a\":1");
assertTrue(json.contains("\"b\":\"string\"")); assertThat(json).contains("\"b\":\"string\"");
} }
@Test @Test
@ -99,14 +96,14 @@ public class MapTest {
Map<String, Integer> map = new LinkedHashMap<>(); Map<String, Integer> map = new LinkedHashMap<>();
Type typeOfMap = new TypeToken<Map<String, Integer>>() {}.getType(); Type typeOfMap = new TypeToken<Map<String, Integer>>() {}.getType();
String json = gson.toJson(map, typeOfMap); String json = gson.toJson(map, typeOfMap);
assertEquals("{}", json); assertThat(json).isEqualTo("{}");
} }
@Test @Test
public void testMapDeserializationEmpty() { public void testMapDeserializationEmpty() {
Type typeOfMap = new TypeToken<Map<String, Integer>>() {}.getType(); Type typeOfMap = new TypeToken<Map<String, Integer>>() {}.getType();
Map<String, Integer> map = gson.fromJson("{}", typeOfMap); Map<String, Integer> map = gson.fromJson("{}", typeOfMap);
assertTrue(map.isEmpty()); assertThat(map).isEmpty();
} }
@Test @Test
@ -117,15 +114,15 @@ public class MapTest {
String json = gson.toJson(map, typeOfMap); String json = gson.toJson(map, typeOfMap);
// Maps are represented as JSON objects, so ignoring null field // Maps are represented as JSON objects, so ignoring null field
assertEquals("{}", json); assertThat(json).isEqualTo("{}");
} }
@Test @Test
public void testMapDeserializationWithNullValue() { public void testMapDeserializationWithNullValue() {
Type typeOfMap = new TypeToken<Map<String, Integer>>() {}.getType(); Type typeOfMap = new TypeToken<Map<String, Integer>>() {}.getType();
Map<String, Integer> map = gson.fromJson("{\"abc\":null}", typeOfMap); Map<String, Integer> map = gson.fromJson("{\"abc\":null}", typeOfMap);
assertEquals(1, map.size()); assertThat(map).hasSize(1);
assertNull(map.get("abc")); assertThat(map.get("abc")).isNull();
} }
@Test @Test
@ -136,7 +133,7 @@ public class MapTest {
Type typeOfMap = new TypeToken<Map<String, Integer>>() {}.getType(); Type typeOfMap = new TypeToken<Map<String, Integer>>() {}.getType();
String json = gson.toJson(map, typeOfMap); String json = gson.toJson(map, typeOfMap);
assertEquals("{\"abc\":null}", json); assertThat(json).isEqualTo("{\"abc\":null}");
} }
@Test @Test
@ -146,21 +143,21 @@ public class MapTest {
Type typeOfMap = new TypeToken<Map<String, Integer>>() {}.getType(); Type typeOfMap = new TypeToken<Map<String, Integer>>() {}.getType();
String json = gson.toJson(map, typeOfMap); String json = gson.toJson(map, typeOfMap);
assertEquals("{\"null\":123}", json); assertThat(json).isEqualTo("{\"null\":123}");
} }
@Test @Test
public void testMapDeserializationWithNullKey() { public void testMapDeserializationWithNullKey() {
Type typeOfMap = new TypeToken<Map<String, Integer>>() {}.getType(); Type typeOfMap = new TypeToken<Map<String, Integer>>() {}.getType();
Map<String, Integer> map = gson.fromJson("{\"null\":123}", typeOfMap); Map<String, Integer> map = gson.fromJson("{\"null\":123}", typeOfMap);
assertEquals(1, map.size()); assertThat(map).hasSize(1);
assertEquals(123, map.get("null").intValue()); assertThat(map.get("null")).isEqualTo(123);
assertNull(map.get(null)); assertThat(map.get(null)).isNull();
map = gson.fromJson("{null:123}", typeOfMap); map = gson.fromJson("{null:123}", typeOfMap);
assertEquals(1, map.size()); assertThat(map).hasSize(1);
assertEquals(123, map.get("null").intValue()); assertThat(map.get("null")).isEqualTo(123);
assertNull(map.get(null)); assertThat(map.get(null)).isNull();
} }
@Test @Test
@ -170,25 +167,25 @@ public class MapTest {
Type typeOfMap = new TypeToken<Map<Integer, String>>() {}.getType(); Type typeOfMap = new TypeToken<Map<Integer, String>>() {}.getType();
String json = gson.toJson(map, typeOfMap); String json = gson.toJson(map, typeOfMap);
assertEquals("{\"123\":\"456\"}", json); assertThat(json).isEqualTo("{\"123\":\"456\"}");
} }
@Test @Test
public void testMapDeserializationWithIntegerKeys() { public void testMapDeserializationWithIntegerKeys() {
Type typeOfMap = new TypeToken<Map<Integer, String>>() {}.getType(); Type typeOfMap = new TypeToken<Map<Integer, String>>() {}.getType();
Map<Integer, String> map = gson.fromJson("{\"123\":\"456\"}", typeOfMap); Map<Integer, String> map = gson.fromJson("{\"123\":\"456\"}", typeOfMap);
assertEquals(1, map.size()); assertThat(map).hasSize(1);
assertTrue(map.containsKey(123)); assertThat(map).containsKey(123);
assertEquals("456", map.get(123)); assertThat(map.get(123)).isEqualTo("456");
} }
@Test @Test
public void testMapDeserializationWithUnquotedIntegerKeys() { public void testMapDeserializationWithUnquotedIntegerKeys() {
Type typeOfMap = new TypeToken<Map<Integer, String>>() {}.getType(); Type typeOfMap = new TypeToken<Map<Integer, String>>() {}.getType();
Map<Integer, String> map = gson.fromJson("{123:\"456\"}", typeOfMap); Map<Integer, String> map = gson.fromJson("{123:\"456\"}", typeOfMap);
assertEquals(1, map.size()); assertThat(map).hasSize(1);
assertTrue(map.containsKey(123)); assertThat(map).containsKey(123);
assertEquals("456", map.get(123)); assertThat(map.get(123)).isEqualTo("456");
} }
@Test @Test
@ -197,9 +194,9 @@ public class MapTest {
String json = String.format("{\"%d\":\"456\"}", longValue); String json = String.format("{\"%d\":\"456\"}", longValue);
Type typeOfMap = new TypeToken<Map<Long, String>>() {}.getType(); Type typeOfMap = new TypeToken<Map<Long, String>>() {}.getType();
Map<Long, String> map = gson.fromJson(json, typeOfMap); Map<Long, String> map = gson.fromJson(json, typeOfMap);
assertEquals(1, map.size()); assertThat(map).hasSize(1);
assertTrue(map.containsKey(longValue)); assertThat(map).containsKey(longValue);
assertEquals("456", map.get(longValue)); assertThat(map.get(longValue)).isEqualTo("456");
} }
@Test @Test
@ -208,71 +205,71 @@ public class MapTest {
String json = String.format("{%d:\"456\"}", longKey); String json = String.format("{%d:\"456\"}", longKey);
Type typeOfMap = new TypeToken<Map<Long, String>>() {}.getType(); Type typeOfMap = new TypeToken<Map<Long, String>>() {}.getType();
Map<Long, String> map = gson.fromJson(json, typeOfMap); Map<Long, String> map = gson.fromJson(json, typeOfMap);
assertEquals(1, map.size()); assertThat(map).hasSize(1);
assertTrue(map.containsKey(longKey)); assertThat(map).containsKey(longKey);
assertEquals("456", map.get(longKey)); assertThat(map.get(longKey)).isEqualTo("456");
} }
@Test @Test
public void testHashMapDeserialization() throws Exception { public void testHashMapDeserialization() {
Type typeOfMap = new TypeToken<HashMap<Integer, String>>() {}.getType(); Type typeOfMap = new TypeToken<HashMap<Integer, String>>() {}.getType();
HashMap<Integer, String> map = gson.fromJson("{\"123\":\"456\"}", typeOfMap); HashMap<Integer, String> map = gson.fromJson("{\"123\":\"456\"}", typeOfMap);
assertEquals(1, map.size()); assertThat(map).hasSize(1);
assertTrue(map.containsKey(123)); assertThat(map).containsKey(123);
assertEquals("456", map.get(123)); assertThat(map.get(123)).isEqualTo("456");
} }
@Test @Test
public void testSortedMap() throws Exception { public void testSortedMap() {
Type typeOfMap = new TypeToken<SortedMap<Integer, String>>() {}.getType(); Type typeOfMap = new TypeToken<SortedMap<Integer, String>>() {}.getType();
SortedMap<Integer, String> map = gson.fromJson("{\"123\":\"456\"}", typeOfMap); SortedMap<Integer, String> map = gson.fromJson("{\"123\":\"456\"}", typeOfMap);
assertEquals(1, map.size()); assertThat(map).hasSize(1);
assertTrue(map.containsKey(123)); assertThat(map).containsKey(123);
assertEquals("456", map.get(123)); assertThat(map.get(123)).isEqualTo("456");
} }
@Test @Test
public void testConcurrentMap() throws Exception { public void testConcurrentMap() {
Type typeOfMap = new TypeToken<ConcurrentMap<Integer, String>>() {}.getType(); Type typeOfMap = new TypeToken<ConcurrentMap<Integer, String>>() {}.getType();
ConcurrentMap<Integer, String> map = gson.fromJson("{\"123\":\"456\"}", typeOfMap); ConcurrentMap<Integer, String> map = gson.fromJson("{\"123\":\"456\"}", typeOfMap);
assertEquals(1, map.size()); assertThat(map).hasSize(1);
assertTrue(map.containsKey(123)); assertThat(map).containsKey(123);
assertEquals("456", map.get(123)); assertThat(map.get(123)).isEqualTo("456");
String json = gson.toJson(map); String json = gson.toJson(map);
assertEquals("{\"123\":\"456\"}", json); assertThat(json).isEqualTo("{\"123\":\"456\"}");
} }
@Test @Test
public void testConcurrentHashMap() throws Exception { public void testConcurrentHashMap() {
Type typeOfMap = new TypeToken<ConcurrentHashMap<Integer, String>>() {}.getType(); Type typeOfMap = new TypeToken<ConcurrentHashMap<Integer, String>>() {}.getType();
ConcurrentHashMap<Integer, String> map = gson.fromJson("{\"123\":\"456\"}", typeOfMap); ConcurrentHashMap<Integer, String> map = gson.fromJson("{\"123\":\"456\"}", typeOfMap);
assertEquals(1, map.size()); assertThat(map).hasSize(1);
assertTrue(map.containsKey(123)); assertThat(map).containsKey(123);
assertEquals("456", map.get(123)); assertThat(map.get(123)).isEqualTo("456");
String json = gson.toJson(map); String json = gson.toJson(map);
assertEquals("{\"123\":\"456\"}", json); assertThat(json).isEqualTo("{\"123\":\"456\"}");
} }
@Test @Test
public void testConcurrentNavigableMap() throws Exception { public void testConcurrentNavigableMap() {
Type typeOfMap = new TypeToken<ConcurrentNavigableMap<Integer, String>>() {}.getType(); Type typeOfMap = new TypeToken<ConcurrentNavigableMap<Integer, String>>() {}.getType();
ConcurrentNavigableMap<Integer, String> map = gson.fromJson("{\"123\":\"456\"}", typeOfMap); ConcurrentNavigableMap<Integer, String> map = gson.fromJson("{\"123\":\"456\"}", typeOfMap);
assertEquals(1, map.size()); assertThat(map).hasSize(1);
assertTrue(map.containsKey(123)); assertThat(map).containsKey(123);
assertEquals("456", map.get(123)); assertThat(map.get(123)).isEqualTo("456");
String json = gson.toJson(map); String json = gson.toJson(map);
assertEquals("{\"123\":\"456\"}", json); assertThat(json).isEqualTo("{\"123\":\"456\"}");
} }
@Test @Test
public void testConcurrentSkipListMap() throws Exception { public void testConcurrentSkipListMap() {
Type typeOfMap = new TypeToken<ConcurrentSkipListMap<Integer, String>>() {}.getType(); Type typeOfMap = new TypeToken<ConcurrentSkipListMap<Integer, String>>() {}.getType();
ConcurrentSkipListMap<Integer, String> map = gson.fromJson("{\"123\":\"456\"}", typeOfMap); ConcurrentSkipListMap<Integer, String> map = gson.fromJson("{\"123\":\"456\"}", typeOfMap);
assertEquals(1, map.size()); assertThat(map).hasSize(1);
assertTrue(map.containsKey(123)); assertThat(map).containsKey(123);
assertEquals("456", map.get(123)); assertThat(map.get(123)).isEqualTo("456");
String json = gson.toJson(map); String json = gson.toJson(map);
assertEquals("{\"123\":\"456\"}", json); assertThat(json).isEqualTo("{\"123\":\"456\"}");
} }
@Test @Test
@ -281,7 +278,7 @@ public class MapTest {
map.put("a", "b"); map.put("a", "b");
Type type = new TypeToken<MyParameterizedMap<String, String>>() {}.getType(); Type type = new TypeToken<MyParameterizedMap<String, String>>() {}.getType();
String json = gson.toJson(map, type); String json = gson.toJson(map, type);
assertTrue(json.contains("\"a\":\"b\"")); assertThat(json).contains("\"a\":\"b\"");
} }
@SuppressWarnings({ "unused", "serial" }) @SuppressWarnings({ "unused", "serial" })
@ -297,7 +294,7 @@ public class MapTest {
MyMap map = new MyMap(); MyMap map = new MyMap();
map.put("a", "b"); map.put("a", "b");
String json = gson.toJson(map, MyMap.class); String json = gson.toJson(map, MyMap.class);
assertTrue(json.contains("\"a\":\"b\"")); assertThat(json).contains("\"a\":\"b\"");
} }
@Test @Test
@ -305,8 +302,8 @@ public class MapTest {
String json = "{a:'1',b:'2'}"; String json = "{a:'1',b:'2'}";
Type type = new TypeToken<LinkedHashMap<String, String>>() {}.getType(); Type type = new TypeToken<LinkedHashMap<String, String>>() {}.getType();
LinkedHashMap<String, Integer> map = gson.fromJson(json, type); LinkedHashMap<String, Integer> map = gson.fromJson(json, type);
assertEquals("1", map.get("a")); assertThat(map).containsEntry("a", "1");
assertEquals("2", map.get("b")); assertThat(map).containsEntry("b", "2");
} }
@Test @Test
@ -318,8 +315,8 @@ public class MapTest {
}).create(); }).create();
String json = "{\"a\":1,\"b\":2}"; String json = "{\"a\":1,\"b\":2}";
MyMap map = gson.fromJson(json, MyMap.class); MyMap map = gson.fromJson(json, MyMap.class);
assertEquals("1", map.get("a")); assertThat(map.get("a")).isEqualTo("1");
assertEquals("2", map.get("b")); assertThat(map.get("b")).isEqualTo("2");
} }
@Test @Test
@ -343,7 +340,7 @@ public class MapTest {
src.put("two", 2L); src.put("two", 2L);
src.put("three", 3L); src.put("three", 3L);
assertEquals("[1,2,3]", gson.toJson(src, type)); assertThat(gson.toJson(src, type)).isEqualTo("[1,2,3]");
} }
/** /**
@ -362,8 +359,8 @@ public class MapTest {
target.map.put("name1", null); target.map.put("name1", null);
target.map.put("name2", "value2"); target.map.put("name2", "value2");
String json = gson.toJson(target); String json = gson.toJson(target);
assertFalse(json.contains("name1")); assertThat(json).doesNotContain("name1");
assertTrue(json.contains("name2")); assertThat(json).contains("name2");
} }
/** /**
@ -376,8 +373,8 @@ public class MapTest {
target.map.put("name1", null); target.map.put("name1", null);
target.map.put("name2", "value2"); target.map.put("name2", "value2");
String json = gson.toJson(target); String json = gson.toJson(target);
assertTrue(json.contains("name1")); assertThat(json).contains("name1");
assertTrue(json.contains("name2")); assertThat(json).contains("name2");
} }
@Test @Test
@ -388,15 +385,15 @@ public class MapTest {
new TypeToken<Map<String, ? extends Collection<? extends Integer>>>() {}.getType(); new TypeToken<Map<String, ? extends Collection<? extends Integer>>>() {}.getType();
String json = gson.toJson(map, typeOfMap); String json = gson.toJson(map, typeOfMap);
assertEquals("{}", json); assertThat(json).isEqualTo("{}");
} }
@Test @Test
public void testMapDeserializationWithWildcardValues() { public void testMapDeserializationWithWildcardValues() {
Type typeOfMap = new TypeToken<Map<String, ? extends Long>>() {}.getType(); Type typeOfMap = new TypeToken<Map<String, ? extends Long>>() {}.getType();
Map<String, ? extends Long> map = gson.fromJson("{\"test\":123}", typeOfMap); Map<String, ? extends Long> map = gson.fromJson("{\"test\":123}", typeOfMap);
assertEquals(1, map.size()); assertThat(map).hasSize(1);
assertEquals(Long.valueOf(123L), map.get("test")); assertThat(map.get("test")).isEqualTo(123L);
} }
@ -418,9 +415,9 @@ public class MapTest {
nestedMap.put("2", "2"); nestedMap.put("2", "2");
map.put("nestedMap", nestedMap); map.put("nestedMap", nestedMap);
String json = gson.toJson(map); String json = gson.toJson(map);
assertTrue(json.contains("nestedMap")); assertThat(json).contains("nestedMap");
assertTrue(json.contains("\"1\":\"1\"")); assertThat(json).contains("\"1\":\"1\"");
assertTrue(json.contains("\"2\":\"2\"")); assertThat(json).contains("\"2\":\"2\"");
} }
/** /**
@ -432,8 +429,8 @@ public class MapTest {
Type type = new TypeToken<Map<String, Map<String, String>>>(){}.getType(); Type type = new TypeToken<Map<String, Map<String, String>>>(){}.getType();
Map<String, Map<String, String>> map = gson.fromJson(json, type); Map<String, Map<String, String>> map = gson.fromJson(json, type);
Map<String, String> nested = map.get("nestedMap"); Map<String, String> nested = map.get("nestedMap");
assertEquals("1", nested.get("1")); assertThat(nested.get("1")).isEqualTo("1");
assertEquals("2", nested.get("2")); assertThat(nested.get("2")).isEqualTo("2");
} }
/** /**
@ -444,7 +441,7 @@ public class MapTest {
Map<String, String> map = new HashMap<>(); Map<String, String> map = new HashMap<>();
map.put("a\"b", "c\"d"); map.put("a\"b", "c\"d");
String json = gson.toJson(map); String json = gson.toJson(map);
assertEquals("{\"a\\\"b\":\"c\\\"d\"}", json); assertThat(json).isEqualTo("{\"a\\\"b\":\"c\\\"d\"}");
} }
/** /**
@ -454,14 +451,14 @@ public class MapTest {
public void testWriteMapsWithEmptyStringKey() { public void testWriteMapsWithEmptyStringKey() {
Map<String, Boolean> map = new HashMap<>(); Map<String, Boolean> map = new HashMap<>();
map.put("", true); map.put("", true);
assertEquals("{\"\":true}", gson.toJson(map)); assertThat(gson.toJson(map)).isEqualTo("{\"\":true}");
} }
@Test @Test
public void testReadMapsWithEmptyStringKey() { public void testReadMapsWithEmptyStringKey() {
Map<String, Boolean> map = gson.fromJson("{\"\":true}", new TypeToken<Map<String, Boolean>>() {}.getType()); Map<String, Boolean> map = gson.fromJson("{\"\":true}", new TypeToken<Map<String, Boolean>>() {}.getType());
assertEquals(Boolean.TRUE, map.get("")); assertThat(map.get("")).isEqualTo(Boolean.TRUE);
} }
/** /**
@ -478,22 +475,21 @@ public class MapTest {
innerMap.put("TestStringArray", new String[] { "one", "two" }); innerMap.put("TestStringArray", new String[] { "one", "two" });
map.put("c", innerMap); map.put("c", innerMap);
assertEquals("{\"a\":12,\"b\":null,\"c\":{\"test\":1,\"TestStringArray\":[\"one\",\"two\"]}}", assertThat(new GsonBuilder().serializeNulls().create().toJson(map))
new GsonBuilder().serializeNulls().create().toJson(map)); .isEqualTo("{\"a\":12,\"b\":null,\"c\":{\"test\":1,\"TestStringArray\":[\"one\",\"two\"]}}");
assertEquals("{\n \"a\": 12,\n \"b\": null,\n \"c\": " assertThat(new GsonBuilder().setPrettyPrinting().serializeNulls().create().toJson(map))
.isEqualTo("{\n \"a\": 12,\n \"b\": null,\n \"c\": "
+ "{\n \"test\": 1,\n \"TestStringArray\": " + "{\n \"test\": 1,\n \"TestStringArray\": "
+ "[\n \"one\",\n \"two\"\n ]\n }\n}", + "[\n \"one\",\n \"two\"\n ]\n }\n}");
new GsonBuilder().setPrettyPrinting().serializeNulls().create().toJson(map)); assertThat(new GsonBuilder().create().toJson(map))
assertEquals("{\"a\":12,\"c\":{\"test\":1,\"TestStringArray\":[\"one\",\"two\"]}}", .isEqualTo("{\"a\":12,\"c\":{\"test\":1,\"TestStringArray\":[\"one\",\"two\"]}}");
new GsonBuilder().create().toJson(map)); assertThat(new GsonBuilder().setPrettyPrinting().create().toJson(map))
assertEquals("{\n \"a\": 12,\n \"c\": " .isEqualTo("{\n \"a\": 12,\n \"c\": "
+ "{\n \"test\": 1,\n \"TestStringArray\": " + "{\n \"test\": 1,\n \"TestStringArray\": "
+ "[\n \"one\",\n \"two\"\n ]\n }\n}", + "[\n \"one\",\n \"two\"\n ]\n }\n}");
new GsonBuilder().setPrettyPrinting().create().toJson(map));
innerMap.put("d", "e"); innerMap.put("d", "e");
assertEquals("{\"a\":12,\"c\":{\"test\":1,\"TestStringArray\":[\"one\",\"two\"],\"d\":\"e\"}}", assertThat(new Gson().toJson(map))
new Gson().toJson(map)); .isEqualTo("{\"a\":12,\"c\":{\"test\":1,\"TestStringArray\":[\"one\",\"two\"],\"d\":\"e\"}}");
} }
@Test @Test
@ -511,11 +507,11 @@ public class MapTest {
.enableComplexMapKeySerialization() .enableComplexMapKeySerialization()
.create(); .create();
String json = gsonWithComplexKeys.toJson(element); String json = gsonWithComplexKeys.toJson(element);
assertEquals(expected, json); assertThat(json).isEqualTo(expected);
Gson gson = new Gson(); Gson gson = new Gson();
json = gson.toJson(element); json = gson.toJson(element);
assertEquals(expected, json); assertThat(json).isEqualTo(expected);
} }
@Test @Test
@ -544,17 +540,17 @@ public class MapTest {
.registerTypeAdapter(TestTypes.Base.class, baseTypeAdapter) .registerTypeAdapter(TestTypes.Base.class, baseTypeAdapter)
.create(); .create();
String json = gson.toJson(element); String json = gson.toJson(element);
assertEquals(expected, json); assertThat(json).isEqualTo(expected);
gson = new GsonBuilder() gson = new GsonBuilder()
.registerTypeAdapter(TestTypes.Base.class, baseTypeAdapter) .registerTypeAdapter(TestTypes.Base.class, baseTypeAdapter)
.create(); .create();
json = gson.toJson(element); json = gson.toJson(element);
assertEquals(expected, json); assertThat(json).isEqualTo(expected);
} }
@Test @Test
public void testGeneralMapField() throws Exception { public void testGeneralMapField() {
MapWithGeneralMapParameters map = new MapWithGeneralMapParameters(); MapWithGeneralMapParameters map = new MapWithGeneralMapParameters();
map.map.put("string", "testString"); map.map.put("string", "testString");
map.map.put("stringArray", new String[]{"one", "two"}); map.map.put("stringArray", new String[]{"one", "two"});
@ -562,12 +558,12 @@ public class MapTest {
String expected = "{\"map\":{\"string\":\"testString\",\"stringArray\":" String expected = "{\"map\":{\"string\":\"testString\",\"stringArray\":"
+ "[\"one\",\"two\"],\"objectArray\":[1,2,\"three\"]}}"; + "[\"one\",\"two\"],\"objectArray\":[1,2,\"three\"]}}";
assertEquals(expected, gson.toJson(map)); assertThat(gson.toJson(map)).isEqualTo(expected);
gson = new GsonBuilder() gson = new GsonBuilder()
.enableComplexMapKeySerialization() .enableComplexMapKeySerialization()
.create(); .create();
assertEquals(expected, gson.toJson(map)); assertThat(gson.toJson(map)).isEqualTo(expected);
} }
@Test @Test
@ -576,8 +572,8 @@ public class MapTest {
map.put(new Point(2, 3), "a"); map.put(new Point(2, 3), "a");
map.put(new Point(5, 7), "b"); map.put(new Point(5, 7), "b");
String json = "{\"2,3\":\"a\",\"5,7\":\"b\"}"; String json = "{\"2,3\":\"a\",\"5,7\":\"b\"}";
assertEquals(json, gson.toJson(map, new TypeToken<Map<Point, String>>() {}.getType())); assertThat(gson.toJson(map, new TypeToken<Map<Point, String>>() {}.getType())).isEqualTo(json);
assertEquals(json, gson.toJson(map, Map.class)); assertThat(gson.toJson(map, Map.class)).isEqualTo(json);
} }
@Test @Test
@ -596,7 +592,7 @@ public class MapTest {
Map<String, String> map = new LinkedHashMap<>(); Map<String, String> map = new LinkedHashMap<>();
map.put("2,3", "a"); map.put("2,3", "a");
map.put("5,7", "b"); map.put("5,7", "b");
assertEquals(map, gson.fromJson(json, new TypeToken<Map<String, String>>() {}.getType())); assertThat(map).isEqualTo(gson.fromJson(json, new TypeToken<Map<String, String>>() {}.getType()));
} }
@Test @Test
@ -605,7 +601,7 @@ public class MapTest {
Map<Double, String> map = new LinkedHashMap<>(); Map<Double, String> map = new LinkedHashMap<>();
map.put(2.3, "a"); map.put(2.3, "a");
map.put(5.7, "b"); map.put(5.7, "b");
assertEquals(map, gson.fromJson(json, new TypeToken<Map<Double, String>>() {}.getType())); assertThat(map).isEqualTo(gson.fromJson(json, new TypeToken<Map<Double, String>>() {}.getType()));
} }
@Test @Test
@ -614,7 +610,7 @@ public class MapTest {
Map<Boolean, String> map = new LinkedHashMap<>(); Map<Boolean, String> map = new LinkedHashMap<>();
map.put(true, "a"); map.put(true, "a");
map.put(false, "b"); map.put(false, "b");
assertEquals(map, gson.fromJson(json, new TypeToken<Map<Boolean, String>>() {}.getType())); assertThat(map).isEqualTo(gson.fromJson(json, new TypeToken<Map<Boolean, String>>() {}.getType()));
} }
@Test @Test
@ -632,8 +628,8 @@ public class MapTest {
Map<String, Map<String, String>> map = newMap( Map<String, Map<String, String>> map = newMap(
"a", newMap("ka1", "va1", "ka2", "va2"), "a", newMap("ka1", "va1", "ka2", "va2"),
"b", newMap("kb1", "vb1", "kb2", "vb2")); "b", newMap("kb1", "vb1", "kb2", "vb2"));
assertEquals("{'a':{'ka1':'va1','ka2':'va2'},'b':{'kb1':'vb1','kb2':'vb2'}}", assertThat(gson.toJson(map, type).replace('"', '\''))
gson.toJson(map, type).replace('"', '\'')); .isEqualTo("{'a':{'ka1':'va1','ka2':'va2'},'b':{'kb1':'vb1','kb2':'vb2'}}");
} }
@Test @Test
@ -643,7 +639,7 @@ public class MapTest {
"a", newMap("ka1", "va1", "ka2", "va2"), "a", newMap("ka1", "va1", "ka2", "va2"),
"b", newMap("kb1", "vb1", "kb2", "vb2")); "b", newMap("kb1", "vb1", "kb2", "vb2"));
String json = "{'a':{'ka1':'va1','ka2':'va2'},'b':{'kb1':'vb1','kb2':'vb2'}}"; String json = "{'a':{'ka1':'va1','ka2':'va2'},'b':{'kb1':'vb1','kb2':'vb2'}}";
assertEquals(map, gson.fromJson(json, type)); assertThat(map).isEqualTo(gson.fromJson(json, type));
} }
private <K, V> Map<K, V> newMap(K key1, V value1, K key2, V value2) { private <K, V> Map<K, V> newMap(K key1, V value1, K key2, V value2) {
@ -659,7 +655,7 @@ public class MapTest {
Map<Double, String> map = new LinkedHashMap<>(); Map<Double, String> map = new LinkedHashMap<>();
map.put(2.3, "a"); map.put(2.3, "a");
JsonElement tree = JsonParser.parseString(json); JsonElement tree = JsonParser.parseString(json);
assertEquals(map, gson.fromJson(tree, new TypeToken<Map<Double, String>>() {}.getType())); assertThat(map).isEqualTo(gson.fromJson(tree, new TypeToken<Map<Double, String>>() {}.getType()));
} }
static class Point { static class Point {

View File

@ -16,10 +16,8 @@
package com.google.gson.functional; package com.google.gson.functional;
import static org.junit.Assert.assertEquals; import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertFalse; import static com.google.common.truth.Truth.assertWithMessage;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.JsonObject; import com.google.gson.JsonObject;
@ -48,8 +46,8 @@ public class MoreSpecificTypeSerializationTest {
public void testSubclassFields() { public void testSubclassFields() {
ClassWithBaseFields target = new ClassWithBaseFields(new Sub(1, 2)); ClassWithBaseFields target = new ClassWithBaseFields(new Sub(1, 2));
String json = gson.toJson(target); String json = gson.toJson(target);
assertTrue(json.contains("\"b\":1")); assertThat(json).contains("\"b\":1");
assertTrue(json.contains("\"s\":2")); assertThat(json).contains("\"s\":2");
} }
@Test @Test
@ -59,8 +57,8 @@ public class MoreSpecificTypeSerializationTest {
list.add(new Sub(2, 3)); list.add(new Sub(2, 3));
ClassWithContainersOfBaseFields target = new ClassWithContainersOfBaseFields(list, null); ClassWithContainersOfBaseFields target = new ClassWithContainersOfBaseFields(list, null);
String json = gson.toJson(target); String json = gson.toJson(target);
assertTrue(json, json.contains("{\"b\":1}")); assertWithMessage(json).that(json).contains("{\"b\":1}");
assertTrue(json, json.contains("{\"s\":3,\"b\":2}")); assertWithMessage(json).that(json).contains("{\"s\":3,\"b\":2}");
} }
@Test @Test
@ -70,10 +68,10 @@ public class MoreSpecificTypeSerializationTest {
map.put("sub", new Sub(2, 3)); map.put("sub", new Sub(2, 3));
ClassWithContainersOfBaseFields target = new ClassWithContainersOfBaseFields(null, map); ClassWithContainersOfBaseFields target = new ClassWithContainersOfBaseFields(null, map);
JsonObject json = gson.toJsonTree(target).getAsJsonObject().get("map").getAsJsonObject(); JsonObject json = gson.toJsonTree(target).getAsJsonObject().get("map").getAsJsonObject();
assertEquals(1, json.get("base").getAsJsonObject().get("b").getAsInt()); assertThat(json.get("base").getAsJsonObject().get("b").getAsInt()).isEqualTo(1);
JsonObject sub = json.get("sub").getAsJsonObject(); JsonObject sub = json.get("sub").getAsJsonObject();
assertEquals(2, sub.get("b").getAsInt()); assertThat(sub.get("b").getAsInt()).isEqualTo(2);
assertEquals(3, sub.get("s").getAsInt()); assertThat(sub.get("s").getAsInt()).isEqualTo(3);
} }
/** /**
@ -84,8 +82,8 @@ public class MoreSpecificTypeSerializationTest {
ClassWithParameterizedBaseFields target = new ClassWithParameterizedBaseFields( ClassWithParameterizedBaseFields target = new ClassWithParameterizedBaseFields(
new ParameterizedSub<>("one", "two")); new ParameterizedSub<>("one", "two"));
String json = gson.toJson(target); String json = gson.toJson(target);
assertTrue(json.contains("\"t\":\"one\"")); assertThat(json).contains("\"t\":\"one\"");
assertFalse(json.contains("\"s\"")); assertThat(json).doesNotContain("\"s\"");
} }
/** /**
@ -100,8 +98,8 @@ public class MoreSpecificTypeSerializationTest {
ClassWithContainersOfParameterizedBaseFields target = ClassWithContainersOfParameterizedBaseFields target =
new ClassWithContainersOfParameterizedBaseFields(list, null); new ClassWithContainersOfParameterizedBaseFields(list, null);
String json = gson.toJson(target); String json = gson.toJson(target);
assertTrue(json, json.contains("{\"t\":\"one\"}")); assertWithMessage(json).that(json).contains("{\"t\":\"one\"}");
assertFalse(json, json.contains("\"s\":")); assertWithMessage(json).that(json).doesNotContain("\"s\":");
} }
/** /**
@ -116,10 +114,10 @@ public class MoreSpecificTypeSerializationTest {
ClassWithContainersOfParameterizedBaseFields target = ClassWithContainersOfParameterizedBaseFields target =
new ClassWithContainersOfParameterizedBaseFields(null, map); new ClassWithContainersOfParameterizedBaseFields(null, map);
JsonObject json = gson.toJsonTree(target).getAsJsonObject().get("map").getAsJsonObject(); JsonObject json = gson.toJsonTree(target).getAsJsonObject().get("map").getAsJsonObject();
assertEquals("one", json.get("base").getAsJsonObject().get("t").getAsString()); assertThat(json.get("base").getAsJsonObject().get("t").getAsString()).isEqualTo("one");
JsonObject sub = json.get("sub").getAsJsonObject(); JsonObject sub = json.get("sub").getAsJsonObject();
assertEquals("two", sub.get("t").getAsString()); assertThat(sub.get("t").getAsString()).isEqualTo("two");
assertNull(sub.get("s")); assertThat(sub.get("s")).isNull();
} }
private static class Base { private static class Base {

View File

@ -15,7 +15,7 @@
*/ */
package com.google.gson.functional; 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.Assert.fail;
import com.google.gson.FieldNamingPolicy; import com.google.gson.FieldNamingPolicy;
@ -47,8 +47,8 @@ public class NamingPolicyTest {
public void testGsonWithNonDefaultFieldNamingPolicySerialization() { public void testGsonWithNonDefaultFieldNamingPolicySerialization() {
Gson gson = builder.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).create(); Gson gson = builder.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).create();
StringWrapper target = new StringWrapper("blah"); StringWrapper target = new StringWrapper("blah");
assertEquals("{\"SomeConstantStringInstanceField\":\"" assertThat(gson.toJson(target)).isEqualTo("{\"SomeConstantStringInstanceField\":\""
+ target.someConstantStringInstanceField + "\"}", gson.toJson(target)); + target.someConstantStringInstanceField + "\"}");
} }
@Test @Test
@ -56,23 +56,23 @@ public class NamingPolicyTest {
Gson gson = builder.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).create(); Gson gson = builder.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).create();
String target = "{\"SomeConstantStringInstanceField\":\"someValue\"}"; String target = "{\"SomeConstantStringInstanceField\":\"someValue\"}";
StringWrapper deserializedObject = gson.fromJson(target, StringWrapper.class); StringWrapper deserializedObject = gson.fromJson(target, StringWrapper.class);
assertEquals("someValue", deserializedObject.someConstantStringInstanceField); assertThat(deserializedObject.someConstantStringInstanceField).isEqualTo("someValue");
} }
@Test @Test
public void testGsonWithLowerCaseDashPolicySerialization() { public void testGsonWithLowerCaseDashPolicySerialization() {
Gson gson = builder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DASHES).create(); Gson gson = builder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DASHES).create();
StringWrapper target = new StringWrapper("blah"); StringWrapper target = new StringWrapper("blah");
assertEquals("{\"some-constant-string-instance-field\":\"" assertThat(gson.toJson(target)).isEqualTo("{\"some-constant-string-instance-field\":\""
+ target.someConstantStringInstanceField + "\"}", gson.toJson(target)); + target.someConstantStringInstanceField + "\"}");
} }
@Test @Test
public void testGsonWithLowerCaseDotPolicySerialization() { public void testGsonWithLowerCaseDotPolicySerialization() {
Gson gson = builder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DOTS).create(); Gson gson = builder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DOTS).create();
StringWrapper target = new StringWrapper("blah"); StringWrapper target = new StringWrapper("blah");
assertEquals("{\"some.constant.string.instance.field\":\"" assertThat(gson.toJson(target)).isEqualTo("{\"some.constant.string.instance.field\":\""
+ target.someConstantStringInstanceField + "\"}", gson.toJson(target)); + target.someConstantStringInstanceField + "\"}");
} }
@Test @Test
@ -80,7 +80,7 @@ public class NamingPolicyTest {
Gson gson = builder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DOTS).create(); Gson gson = builder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DOTS).create();
String target = "{\"some.constant.string.instance.field\":\"someValue\"}"; String target = "{\"some.constant.string.instance.field\":\"someValue\"}";
StringWrapper deserializedObject = gson.fromJson(target, StringWrapper.class); StringWrapper deserializedObject = gson.fromJson(target, StringWrapper.class);
assertEquals("someValue", deserializedObject.someConstantStringInstanceField); assertThat(deserializedObject.someConstantStringInstanceField).isEqualTo("someValue");
} }
@Test @Test
@ -88,7 +88,7 @@ public class NamingPolicyTest {
Gson gson = builder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DASHES).create(); Gson gson = builder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DASHES).create();
String target = "{\"some-constant-string-instance-field\":\"someValue\"}"; String target = "{\"some-constant-string-instance-field\":\"someValue\"}";
StringWrapper deserializedObject = gson.fromJson(target, StringWrapper.class); StringWrapper deserializedObject = gson.fromJson(target, StringWrapper.class);
assertEquals("someValue", deserializedObject.someConstantStringInstanceField); assertThat(deserializedObject.someConstantStringInstanceField).isEqualTo("someValue");
} }
@Test @Test
@ -96,8 +96,8 @@ public class NamingPolicyTest {
Gson gson = builder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) Gson gson = builder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
.create(); .create();
StringWrapper target = new StringWrapper("blah"); StringWrapper target = new StringWrapper("blah");
assertEquals("{\"some_constant_string_instance_field\":\"" assertThat(gson.toJson(target)).isEqualTo("{\"some_constant_string_instance_field\":\""
+ target.someConstantStringInstanceField + "\"}", gson.toJson(target)); + target.someConstantStringInstanceField + "\"}");
} }
@Test @Test
@ -106,7 +106,7 @@ public class NamingPolicyTest {
.create(); .create();
String target = "{\"some_constant_string_instance_field\":\"someValue\"}"; String target = "{\"some_constant_string_instance_field\":\"someValue\"}";
StringWrapper deserializedObject = gson.fromJson(target, StringWrapper.class); StringWrapper deserializedObject = gson.fromJson(target, StringWrapper.class);
assertEquals("someValue", deserializedObject.someConstantStringInstanceField); assertThat(deserializedObject.someConstantStringInstanceField).isEqualTo("someValue");
} }
@Test @Test
@ -114,7 +114,7 @@ public class NamingPolicyTest {
Gson gson = builder.create(); Gson gson = builder.create();
ClassWithSerializedNameFields expected = new ClassWithSerializedNameFields(5, 6); ClassWithSerializedNameFields expected = new ClassWithSerializedNameFields(5, 6);
String actual = gson.toJson(expected); String actual = gson.toJson(expected);
assertEquals(expected.getExpectedJson(), actual); assertThat(actual).isEqualTo(expected.getExpectedJson());
} }
@Test @Test
@ -123,7 +123,7 @@ public class NamingPolicyTest {
ClassWithSerializedNameFields expected = new ClassWithSerializedNameFields(5, 7); ClassWithSerializedNameFields expected = new ClassWithSerializedNameFields(5, 7);
ClassWithSerializedNameFields actual = ClassWithSerializedNameFields actual =
gson.fromJson(expected.getExpectedJson(), ClassWithSerializedNameFields.class); gson.fromJson(expected.getExpectedJson(), ClassWithSerializedNameFields.class);
assertEquals(expected.f, actual.f); assertThat(actual.f).isEqualTo(expected.f);
} }
@Test @Test
@ -134,12 +134,10 @@ public class NamingPolicyTest {
gson.toJson(target); gson.toJson(target);
fail(); fail();
} catch (IllegalArgumentException expected) { } catch (IllegalArgumentException expected) {
assertEquals( assertThat(expected).hasMessageThat()
"Class com.google.gson.functional.NamingPolicyTest$ClassWithDuplicateFields declares multiple JSON fields named 'a';" .isEqualTo("Class com.google.gson.functional.NamingPolicyTest$ClassWithDuplicateFields declares multiple JSON fields named 'a';"
+ " conflict is caused by fields com.google.gson.functional.NamingPolicyTest$ClassWithDuplicateFields#a and" + " conflict is caused by fields com.google.gson.functional.NamingPolicyTest$ClassWithDuplicateFields#a and"
+ " com.google.gson.functional.NamingPolicyTest$ClassWithDuplicateFields#b", + " com.google.gson.functional.NamingPolicyTest$ClassWithDuplicateFields#b");
expected.getMessage()
);
} }
} }
@ -148,8 +146,8 @@ public class NamingPolicyTest {
Gson gson = builder.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE_WITH_SPACES) Gson gson = builder.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE_WITH_SPACES)
.create(); .create();
StringWrapper target = new StringWrapper("blah"); StringWrapper target = new StringWrapper("blah");
assertEquals("{\"Some Constant String Instance Field\":\"" assertThat(gson.toJson(target)).isEqualTo("{\"Some Constant String Instance Field\":\""
+ target.someConstantStringInstanceField + "\"}", gson.toJson(target)); + target.someConstantStringInstanceField + "\"}");
} }
@Test @Test
@ -158,7 +156,7 @@ public class NamingPolicyTest {
.create(); .create();
String target = "{\"Some Constant String Instance Field\":\"someValue\"}"; String target = "{\"Some Constant String Instance Field\":\"someValue\"}";
StringWrapper deserializedObject = gson.fromJson(target, StringWrapper.class); StringWrapper deserializedObject = gson.fromJson(target, StringWrapper.class);
assertEquals("someValue", deserializedObject.someConstantStringInstanceField); assertThat(deserializedObject.someConstantStringInstanceField).isEqualTo("someValue");
} }
@Test @Test
@ -166,8 +164,8 @@ public class NamingPolicyTest {
Gson gson = builder.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CASE_WITH_UNDERSCORES) Gson gson = builder.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CASE_WITH_UNDERSCORES)
.create(); .create();
StringWrapper target = new StringWrapper("blah"); StringWrapper target = new StringWrapper("blah");
assertEquals("{\"SOME_CONSTANT_STRING_INSTANCE_FIELD\":\"" assertThat(gson.toJson(target)).isEqualTo("{\"SOME_CONSTANT_STRING_INSTANCE_FIELD\":\""
+ target.someConstantStringInstanceField + "\"}", gson.toJson(target)); + target.someConstantStringInstanceField + "\"}");
} }
@Test @Test
@ -176,32 +174,32 @@ public class NamingPolicyTest {
.create(); .create();
String target = "{\"SOME_CONSTANT_STRING_INSTANCE_FIELD\":\"someValue\"}"; String target = "{\"SOME_CONSTANT_STRING_INSTANCE_FIELD\":\"someValue\"}";
StringWrapper deserializedObject = gson.fromJson(target, StringWrapper.class); StringWrapper deserializedObject = gson.fromJson(target, StringWrapper.class);
assertEquals("someValue", deserializedObject.someConstantStringInstanceField); assertThat(deserializedObject.someConstantStringInstanceField).isEqualTo("someValue");
} }
@Test @Test
public void testDeprecatedNamingStrategy() throws Exception { public void testDeprecatedNamingStrategy() {
Gson gson = builder.setFieldNamingStrategy(new UpperCaseNamingStrategy()).create(); Gson gson = builder.setFieldNamingStrategy(new UpperCaseNamingStrategy()).create();
ClassWithDuplicateFields target = new ClassWithDuplicateFields(10); ClassWithDuplicateFields target = new ClassWithDuplicateFields(10);
String actual = gson.toJson(target); String actual = gson.toJson(target);
assertEquals("{\"A\":10}", actual); assertThat(actual).isEqualTo("{\"A\":10}");
} }
@Test @Test
public void testComplexFieldNameStrategy() throws Exception { public void testComplexFieldNameStrategy() {
Gson gson = new Gson(); Gson gson = new Gson();
String json = gson.toJson(new ClassWithComplexFieldName(10)); String json = gson.toJson(new ClassWithComplexFieldName(10));
String escapedFieldName = "@value\\\"_s$\\\\"; String escapedFieldName = "@value\\\"_s$\\\\";
assertEquals("{\"" + escapedFieldName + "\":10}", json); assertThat(json).isEqualTo("{\"" + escapedFieldName + "\":10}");
ClassWithComplexFieldName obj = gson.fromJson(json, ClassWithComplexFieldName.class); ClassWithComplexFieldName obj = gson.fromJson(json, ClassWithComplexFieldName.class);
assertEquals(10, obj.value); assertThat(obj.value).isEqualTo(10);
} }
/** http://code.google.com/p/google-gson/issues/detail?id=349 */ /** http://code.google.com/p/google-gson/issues/detail?id=349 */
@Test @Test
public void testAtSignInSerializedName() { public void testAtSignInSerializedName() {
assertEquals("{\"@foo\":\"bar\"}", new Gson().toJson(new AtName())); assertThat(new Gson().toJson(new AtName())).isEqualTo("{\"@foo\":\"bar\"}");
} }
static final class AtName { static final class AtName {

View File

@ -16,10 +16,7 @@
package com.google.gson.functional; package com.google.gson.functional;
import static org.junit.Assert.assertEquals; import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;
@ -55,17 +52,17 @@ public class NullObjectAndFieldTest {
public void testTopLevelNullObjectSerialization() { public void testTopLevelNullObjectSerialization() {
Gson gson = gsonBuilder.create(); Gson gson = gsonBuilder.create();
String actual = gson.toJson(null); String actual = gson.toJson(null);
assertEquals("null", actual); assertThat(actual).isEqualTo("null");
actual = gson.toJson(null, String.class); actual = gson.toJson(null, String.class);
assertEquals("null", actual); assertThat(actual).isEqualTo("null");
} }
@Test @Test
public void testTopLevelNullObjectDeserialization() throws Exception { public void testTopLevelNullObjectDeserialization() {
Gson gson = gsonBuilder.create(); Gson gson = gsonBuilder.create();
String actual = gson.fromJson("null", String.class); String actual = gson.fromJson("null", String.class);
assertNull(actual); assertThat(actual).isNull();
} }
@Test @Test
@ -74,14 +71,14 @@ public class NullObjectAndFieldTest {
ClassWithObjects target = new ClassWithObjects(null); ClassWithObjects target = new ClassWithObjects(null);
String actual = gson.toJson(target); String actual = gson.toJson(target);
String expected = "{\"bag\":null}"; String expected = "{\"bag\":null}";
assertEquals(expected, actual); assertThat(actual).isEqualTo(expected);
} }
@Test @Test
public void testExplicitDeserializationOfNulls() throws Exception { public void testExplicitDeserializationOfNulls() {
Gson gson = gsonBuilder.create(); Gson gson = gsonBuilder.create();
ClassWithObjects target = gson.fromJson("{\"bag\":null}", ClassWithObjects.class); ClassWithObjects target = gson.fromJson("{\"bag\":null}", ClassWithObjects.class);
assertNull(target.bag); assertThat(target.bag).isNull();
} }
@Test @Test
@ -89,7 +86,7 @@ public class NullObjectAndFieldTest {
Gson gson = gsonBuilder.create(); Gson gson = gsonBuilder.create();
ClassWithMembers target = new ClassWithMembers(); ClassWithMembers target = new ClassWithMembers();
String json = gson.toJson(target); String json = gson.toJson(target);
assertTrue(json.contains("\"array\":null")); assertThat(json).contains("\"array\":null");
} }
/** /**
@ -100,7 +97,7 @@ public class NullObjectAndFieldTest {
Gson gson = gsonBuilder.serializeNulls().create(); Gson gson = gsonBuilder.serializeNulls().create();
ClassWithNullWrappedPrimitive target = new ClassWithNullWrappedPrimitive(); ClassWithNullWrappedPrimitive target = new ClassWithNullWrappedPrimitive();
String json = gson.toJson(target); String json = gson.toJson(target);
assertTrue(json.contains("\"value\":null")); assertThat(json).contains("\"value\":null");
} }
/** /**
@ -111,7 +108,7 @@ public class NullObjectAndFieldTest {
Gson gson = gsonBuilder.create(); Gson gson = gsonBuilder.create();
String json = "{'value':null}"; String json = "{'value':null}";
ClassWithNullWrappedPrimitive target = gson.fromJson(json, ClassWithNullWrappedPrimitive.class); ClassWithNullWrappedPrimitive target = gson.fromJson(json, ClassWithNullWrappedPrimitive.class);
assertNull(target.value); assertThat(target.value).isNull();
} }
@Test @Test
@ -119,7 +116,7 @@ public class NullObjectAndFieldTest {
Gson gson = gsonBuilder.create(); Gson gson = gsonBuilder.create();
ClassWithMembers target = new ClassWithMembers(); ClassWithMembers target = new ClassWithMembers();
String json = gson.toJson(target); String json = gson.toJson(target);
assertTrue(json.contains("\"col\":null")); assertThat(json).contains("\"col\":null");
} }
@Test @Test
@ -127,7 +124,7 @@ public class NullObjectAndFieldTest {
Gson gson = gsonBuilder.create(); Gson gson = gsonBuilder.create();
ClassWithMembers target = new ClassWithMembers(); ClassWithMembers target = new ClassWithMembers();
String json = gson.toJson(target); String json = gson.toJson(target);
assertTrue(json.contains("\"str\":null")); assertThat(json).contains("\"str\":null");
} }
@Test @Test
@ -137,31 +134,31 @@ public class NullObjectAndFieldTest {
ClassWithObjects target = new ClassWithObjects(new BagOfPrimitives()); ClassWithObjects target = new ClassWithObjects(new BagOfPrimitives());
String actual = gson.toJson(target); String actual = gson.toJson(target);
String expected = "{\"bag\":null}"; String expected = "{\"bag\":null}";
assertEquals(expected, actual); assertThat(actual).isEqualTo(expected);
} }
@Test @Test
public void testPrintPrintingObjectWithNulls() throws Exception { public void testPrintPrintingObjectWithNulls() {
gsonBuilder = new GsonBuilder(); gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create(); Gson gson = gsonBuilder.create();
String result = gson.toJson(new ClassWithMembers()); String result = gson.toJson(new ClassWithMembers());
assertEquals("{}", result); assertThat(result).isEqualTo("{}");
gson = gsonBuilder.serializeNulls().create(); gson = gsonBuilder.serializeNulls().create();
result = gson.toJson(new ClassWithMembers()); result = gson.toJson(new ClassWithMembers());
assertTrue(result.contains("\"str\":null")); assertThat(result).contains("\"str\":null");
} }
@Test @Test
public void testPrintPrintingArraysWithNulls() throws Exception { public void testPrintPrintingArraysWithNulls() {
gsonBuilder = new GsonBuilder(); gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create(); Gson gson = gsonBuilder.create();
String result = gson.toJson(new String[] { "1", null, "3" }); String result = gson.toJson(new String[] { "1", null, "3" });
assertEquals("[\"1\",null,\"3\"]", result); assertThat(result).isEqualTo("[\"1\",null,\"3\"]");
gson = gsonBuilder.serializeNulls().create(); gson = gsonBuilder.serializeNulls().create();
result = gson.toJson(new String[] { "1", null, "3" }); result = gson.toJson(new String[] { "1", null, "3" });
assertEquals("[\"1\",null,\"3\"]", result); assertThat(result).isEqualTo("[\"1\",null,\"3\"]");
} }
// test for issue 389 // test for issue 389
@ -170,13 +167,14 @@ public class NullObjectAndFieldTest {
Gson gson = new Gson(); Gson gson = new Gson();
ClassWithInitializedMembers target = ClassWithInitializedMembers target =
gson.fromJson("{array:[1,2,3]}", ClassWithInitializedMembers.class); gson.fromJson("{array:[1,2,3]}", ClassWithInitializedMembers.class);
assertTrue(target.array.length == 3 && target.array[1] == 2); assertThat(target.array).hasLength(3);
assertEquals(ClassWithInitializedMembers.MY_STRING_DEFAULT, target.str1); assertThat(target.array[1]).isEqualTo(2);
assertNull(target.str2); assertThat(target.str1).isEqualTo(ClassWithInitializedMembers.MY_STRING_DEFAULT);
assertEquals(ClassWithInitializedMembers.MY_INT_DEFAULT, target.int1); assertThat(target.str2).isNull();
assertEquals(0, target.int2); // test the default value of a primitive int field per JVM spec assertThat(target.int1).isEqualTo(ClassWithInitializedMembers.MY_INT_DEFAULT);
assertEquals(ClassWithInitializedMembers.MY_BOOLEAN_DEFAULT, target.bool1); assertThat(target.int2).isEqualTo(0); // test the default value of a primitive int field per JVM spec
assertFalse(target.bool2); // test the default value of a primitive boolean field per JVM spec assertThat(target.bool1).isEqualTo(ClassWithInitializedMembers.MY_BOOLEAN_DEFAULT);
assertThat(target.bool2).isFalse(); // test the default value of a primitive boolean field per JVM spec
} }
public static class ClassWithInitializedMembers { public static class ClassWithInitializedMembers {
@ -221,7 +219,7 @@ public class NullObjectAndFieldTest {
Gson gson = new Gson(); Gson gson = new Gson();
String json = "{value:null}"; String json = "{value:null}";
ObjectWithField obj = gson.fromJson(json, ObjectWithField.class); ObjectWithField obj = gson.fromJson(json, ObjectWithField.class);
assertNull(obj.value); assertThat(obj.value).isNull();
} }
@Test @Test
@ -236,7 +234,7 @@ public class NullObjectAndFieldTest {
ObjectWithField target = new ObjectWithField(); ObjectWithField target = new ObjectWithField();
target.value = "value1"; target.value = "value1";
String json = gson.toJson(target); String json = gson.toJson(target);
assertFalse(json.contains("value1")); assertThat(json).doesNotContain("value1");
} }
@Test @Test
@ -250,7 +248,7 @@ public class NullObjectAndFieldTest {
}).create(); }).create();
String json = "{value:'value1'}"; String json = "{value:'value1'}";
ObjectWithField target = gson.fromJson(json, ObjectWithField.class); ObjectWithField target = gson.fromJson(json, ObjectWithField.class);
assertNull(target); assertThat(target).isNull();
} }
private static class ObjectWithField { private static class ObjectWithField {

View File

@ -16,12 +16,7 @@
package com.google.gson.functional; package com.google.gson.functional;
import static org.junit.Assert.assertEquals; import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import com.google.gson.Gson; import com.google.gson.Gson;
@ -79,7 +74,7 @@ public class ObjectTest {
} }
@After @After
public void tearDown() throws Exception { public void tearDown() {
TimeZone.setDefault(oldTimeZone); TimeZone.setDefault(oldTimeZone);
Locale.setDefault(oldLocale); Locale.setDefault(oldLocale);
} }
@ -88,80 +83,79 @@ public class ObjectTest {
public void testJsonInSingleQuotesDeserialization() { public void testJsonInSingleQuotesDeserialization() {
String json = "{'stringValue':'no message','intValue':10,'longValue':20}"; String json = "{'stringValue':'no message','intValue':10,'longValue':20}";
BagOfPrimitives target = gson.fromJson(json, BagOfPrimitives.class); BagOfPrimitives target = gson.fromJson(json, BagOfPrimitives.class);
assertEquals("no message", target.stringValue); assertThat(target.stringValue).isEqualTo("no message");
assertEquals(10, target.intValue); assertThat(target.intValue).isEqualTo(10);
assertEquals(20, target.longValue); assertThat(target.longValue).isEqualTo(20);
} }
@Test @Test
public void testJsonInMixedQuotesDeserialization() { public void testJsonInMixedQuotesDeserialization() {
String json = "{\"stringValue\":'no message','intValue':10,'longValue':20}"; String json = "{\"stringValue\":'no message','intValue':10,'longValue':20}";
BagOfPrimitives target = gson.fromJson(json, BagOfPrimitives.class); BagOfPrimitives target = gson.fromJson(json, BagOfPrimitives.class);
assertEquals("no message", target.stringValue); assertThat(target.stringValue).isEqualTo("no message");
assertEquals(10, target.intValue); assertThat(target.intValue).isEqualTo(10);
assertEquals(20, target.longValue); assertThat(target.longValue).isEqualTo(20);
} }
@Test @Test
public void testBagOfPrimitivesSerialization() throws Exception { public void testBagOfPrimitivesSerialization() {
BagOfPrimitives target = new BagOfPrimitives(10, 20, false, "stringValue"); BagOfPrimitives target = new BagOfPrimitives(10, 20, false, "stringValue");
assertEquals(target.getExpectedJson(), gson.toJson(target)); assertThat(gson.toJson(target)).isEqualTo(target.getExpectedJson());
} }
@Test @Test
public void testBagOfPrimitivesDeserialization() throws Exception { public void testBagOfPrimitivesDeserialization() {
BagOfPrimitives src = new BagOfPrimitives(10, 20, false, "stringValue"); BagOfPrimitives src = new BagOfPrimitives(10, 20, false, "stringValue");
String json = src.getExpectedJson(); String json = src.getExpectedJson();
BagOfPrimitives target = gson.fromJson(json, BagOfPrimitives.class); BagOfPrimitives target = gson.fromJson(json, BagOfPrimitives.class);
assertEquals(json, target.getExpectedJson()); assertThat(target.getExpectedJson()).isEqualTo(json);
} }
@Test @Test
public void testBagOfPrimitiveWrappersSerialization() throws Exception { public void testBagOfPrimitiveWrappersSerialization() {
BagOfPrimitiveWrappers target = new BagOfPrimitiveWrappers(10L, 20, false); BagOfPrimitiveWrappers target = new BagOfPrimitiveWrappers(10L, 20, false);
assertEquals(target.getExpectedJson(), gson.toJson(target)); assertThat(gson.toJson(target)).isEqualTo(target.getExpectedJson());
} }
@Test @Test
public void testBagOfPrimitiveWrappersDeserialization() throws Exception { public void testBagOfPrimitiveWrappersDeserialization() {
BagOfPrimitiveWrappers target = new BagOfPrimitiveWrappers(10L, 20, false); BagOfPrimitiveWrappers target = new BagOfPrimitiveWrappers(10L, 20, false);
String jsonString = target.getExpectedJson(); String jsonString = target.getExpectedJson();
target = gson.fromJson(jsonString, BagOfPrimitiveWrappers.class); target = gson.fromJson(jsonString, BagOfPrimitiveWrappers.class);
assertEquals(jsonString, target.getExpectedJson()); assertThat(target.getExpectedJson()).isEqualTo(jsonString);
} }
@Test @Test
public void testClassWithTransientFieldsSerialization() throws Exception { public void testClassWithTransientFieldsSerialization() {
ClassWithTransientFields<Long> target = new ClassWithTransientFields<>(1L); ClassWithTransientFields<Long> target = new ClassWithTransientFields<>(1L);
assertEquals(target.getExpectedJson(), gson.toJson(target)); assertThat(gson.toJson(target)).isEqualTo(target.getExpectedJson());
} }
@Test @Test
public void testClassWithTransientFieldsDeserialization() throws Exception { public void testClassWithTransientFieldsDeserialization() {
String json = "{\"longValue\":[1]}"; String json = "{\"longValue\":[1]}";
ClassWithTransientFields<?> target = gson.fromJson(json, ClassWithTransientFields.class); ClassWithTransientFields<?> target = gson.fromJson(json, ClassWithTransientFields.class);
assertEquals(json, target.getExpectedJson()); assertThat(target.getExpectedJson()).isEqualTo(json);
} }
@Test @Test
public void testClassWithTransientFieldsDeserializationTransientFieldsPassedInJsonAreIgnored() public void testClassWithTransientFieldsDeserializationTransientFieldsPassedInJsonAreIgnored() {
throws Exception {
String json = "{\"transientLongValue\":1,\"longValue\":[1]}"; String json = "{\"transientLongValue\":1,\"longValue\":[1]}";
ClassWithTransientFields<?> target = gson.fromJson(json, ClassWithTransientFields.class); ClassWithTransientFields<?> target = gson.fromJson(json, ClassWithTransientFields.class);
assertFalse(target.transientLongValue != 1); assertThat(target.transientLongValue != 1).isFalse();
} }
@Test @Test
public void testClassWithNoFieldsSerialization() throws Exception { public void testClassWithNoFieldsSerialization() {
assertEquals("{}", gson.toJson(new ClassWithNoFields())); assertThat(gson.toJson(new ClassWithNoFields())).isEqualTo("{}");
} }
@Test @Test
public void testClassWithNoFieldsDeserialization() throws Exception { public void testClassWithNoFieldsDeserialization() {
String json = "{}"; String json = "{}";
ClassWithNoFields target = gson.fromJson(json, ClassWithNoFields.class); ClassWithNoFields target = gson.fromJson(json, ClassWithNoFields.class);
ClassWithNoFields expected = new ClassWithNoFields(); ClassWithNoFields expected = new ClassWithNoFields();
assertEquals(expected, target); assertThat(target).isEqualTo(expected);
} }
private static class Subclass extends Superclass1 { private static class Subclass extends Superclass1 {
@ -181,39 +175,36 @@ public class ObjectTest {
gson.getAdapter(Subclass.class); gson.getAdapter(Subclass.class);
fail(); fail();
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
assertEquals( assertThat(e).hasMessageThat().isEqualTo("Class com.google.gson.functional.ObjectTest$Subclass declares multiple JSON fields named 's';"
"Class com.google.gson.functional.ObjectTest$Subclass declares multiple JSON fields named 's';"
+ " conflict is caused by fields com.google.gson.functional.ObjectTest$Superclass1#s and" + " conflict is caused by fields com.google.gson.functional.ObjectTest$Superclass1#s and"
+ " com.google.gson.functional.ObjectTest$Superclass2#s", + " com.google.gson.functional.ObjectTest$Superclass2#s");
e.getMessage()
);
} }
} }
@Test @Test
public void testNestedSerialization() throws Exception { public void testNestedSerialization() {
Nested target = new Nested(new BagOfPrimitives(10, 20, false, "stringValue"), Nested target = new Nested(new BagOfPrimitives(10, 20, false, "stringValue"),
new BagOfPrimitives(30, 40, true, "stringValue")); new BagOfPrimitives(30, 40, true, "stringValue"));
assertEquals(target.getExpectedJson(), gson.toJson(target)); assertThat(gson.toJson(target)).isEqualTo(target.getExpectedJson());
} }
@Test @Test
public void testNestedDeserialization() throws Exception { public void testNestedDeserialization() {
String json = "{\"primitive1\":{\"longValue\":10,\"intValue\":20,\"booleanValue\":false," String json = "{\"primitive1\":{\"longValue\":10,\"intValue\":20,\"booleanValue\":false,"
+ "\"stringValue\":\"stringValue\"},\"primitive2\":{\"longValue\":30,\"intValue\":40," + "\"stringValue\":\"stringValue\"},\"primitive2\":{\"longValue\":30,\"intValue\":40,"
+ "\"booleanValue\":true,\"stringValue\":\"stringValue\"}}"; + "\"booleanValue\":true,\"stringValue\":\"stringValue\"}}";
Nested target = gson.fromJson(json, Nested.class); Nested target = gson.fromJson(json, Nested.class);
assertEquals(json, target.getExpectedJson()); assertThat(target.getExpectedJson()).isEqualTo(json);
} }
@Test @Test
public void testNullSerialization() throws Exception { public void testNullSerialization() {
assertEquals("null", gson.toJson(null)); assertThat(gson.toJson(null)).isEqualTo("null");
} }
@Test @Test
public void testEmptyStringDeserialization() throws Exception { public void testEmptyStringDeserialization() {
Object object = gson.fromJson("", Object.class); Object object = gson.fromJson("", Object.class);
assertNull(object); assertThat(object).isNull();
} }
@Test @Test
@ -226,54 +217,54 @@ public class ObjectTest {
} }
@Test @Test
public void testNullDeserialization() throws Exception { public void testNullDeserialization() {
String myNullObject = null; String myNullObject = null;
Object object = gson.fromJson(myNullObject, Object.class); Object object = gson.fromJson(myNullObject, Object.class);
assertNull(object); assertThat(object).isNull();
} }
@Test @Test
public void testNullFieldsSerialization() throws Exception { public void testNullFieldsSerialization() {
Nested target = new Nested(new BagOfPrimitives(10, 20, false, "stringValue"), null); Nested target = new Nested(new BagOfPrimitives(10, 20, false, "stringValue"), null);
assertEquals(target.getExpectedJson(), gson.toJson(target)); assertThat(gson.toJson(target)).isEqualTo(target.getExpectedJson());
} }
@Test @Test
public void testNullFieldsDeserialization() throws Exception { public void testNullFieldsDeserialization() {
String json = "{\"primitive1\":{\"longValue\":10,\"intValue\":20,\"booleanValue\":false" String json = "{\"primitive1\":{\"longValue\":10,\"intValue\":20,\"booleanValue\":false"
+ ",\"stringValue\":\"stringValue\"}}"; + ",\"stringValue\":\"stringValue\"}}";
Nested target = gson.fromJson(json, Nested.class); Nested target = gson.fromJson(json, Nested.class);
assertEquals(json, target.getExpectedJson()); assertThat(target.getExpectedJson()).isEqualTo(json);
} }
@Test @Test
public void testArrayOfObjectsSerialization() throws Exception { public void testArrayOfObjectsSerialization() {
ArrayOfObjects target = new ArrayOfObjects(); ArrayOfObjects target = new ArrayOfObjects();
assertEquals(target.getExpectedJson(), gson.toJson(target)); assertThat(gson.toJson(target)).isEqualTo(target.getExpectedJson());
} }
@Test @Test
public void testArrayOfObjectsDeserialization() throws Exception { public void testArrayOfObjectsDeserialization() {
String json = new ArrayOfObjects().getExpectedJson(); String json = new ArrayOfObjects().getExpectedJson();
ArrayOfObjects target = gson.fromJson(json, ArrayOfObjects.class); ArrayOfObjects target = gson.fromJson(json, ArrayOfObjects.class);
assertEquals(json, target.getExpectedJson()); assertThat(target.getExpectedJson()).isEqualTo(json);
} }
@Test @Test
public void testArrayOfArraysSerialization() throws Exception { public void testArrayOfArraysSerialization() {
ArrayOfArrays target = new ArrayOfArrays(); ArrayOfArrays target = new ArrayOfArrays();
assertEquals(target.getExpectedJson(), gson.toJson(target)); assertThat(gson.toJson(target)).isEqualTo(target.getExpectedJson());
} }
@Test @Test
public void testArrayOfArraysDeserialization() throws Exception { public void testArrayOfArraysDeserialization() {
String json = new ArrayOfArrays().getExpectedJson(); String json = new ArrayOfArrays().getExpectedJson();
ArrayOfArrays target = gson.fromJson(json, ArrayOfArrays.class); ArrayOfArrays target = gson.fromJson(json, ArrayOfArrays.class);
assertEquals(json, target.getExpectedJson()); assertThat(target.getExpectedJson()).isEqualTo(json);
} }
@Test @Test
public void testArrayOfObjectsAsFields() throws Exception { public void testArrayOfObjectsAsFields() {
ClassWithObjects classWithObjects = new ClassWithObjects(); ClassWithObjects classWithObjects = new ClassWithObjects();
BagOfPrimitives bagOfPrimitives = new BagOfPrimitives(); BagOfPrimitives bagOfPrimitives = new BagOfPrimitives();
String stringValue = "someStringValueInArray"; String stringValue = "someStringValueInArray";
@ -284,37 +275,37 @@ public class ObjectTest {
new Object[] { stringValue, classWithObjects, bagOfPrimitives }); new Object[] { stringValue, classWithObjects, bagOfPrimitives });
String json = gson.toJson(classWithArray); String json = gson.toJson(classWithArray);
assertTrue(json.contains(classWithObjectsJson)); assertThat(json).contains(classWithObjectsJson);
assertTrue(json.contains(bagOfPrimitivesJson)); assertThat(json).contains(bagOfPrimitivesJson);
assertTrue(json.contains("\"" + stringValue + "\"")); assertThat(json).contains("\"" + stringValue + "\"");
} }
/** /**
* Created in response to Issue 14: http://code.google.com/p/google-gson/issues/detail?id=14 * Created in response to Issue 14: http://code.google.com/p/google-gson/issues/detail?id=14
*/ */
@Test @Test
public void testNullArraysDeserialization() throws Exception { public void testNullArraysDeserialization() {
String json = "{\"array\": null}"; String json = "{\"array\": null}";
ClassWithArray target = gson.fromJson(json, ClassWithArray.class); ClassWithArray target = gson.fromJson(json, ClassWithArray.class);
assertNull(target.array); assertThat(target.array).isNull();
} }
/** /**
* Created in response to Issue 14: http://code.google.com/p/google-gson/issues/detail?id=14 * Created in response to Issue 14: http://code.google.com/p/google-gson/issues/detail?id=14
*/ */
@Test @Test
public void testNullObjectFieldsDeserialization() throws Exception { public void testNullObjectFieldsDeserialization() {
String json = "{\"bag\": null}"; String json = "{\"bag\": null}";
ClassWithObjects target = gson.fromJson(json, ClassWithObjects.class); ClassWithObjects target = gson.fromJson(json, ClassWithObjects.class);
assertNull(target.bag); assertThat(target.bag).isNull();
} }
@Test @Test
public void testEmptyCollectionInAnObjectDeserialization() throws Exception { public void testEmptyCollectionInAnObjectDeserialization() {
String json = "{\"children\":[]}"; String json = "{\"children\":[]}";
ClassWithCollectionField target = gson.fromJson(json, ClassWithCollectionField.class); ClassWithCollectionField target = gson.fromJson(json, ClassWithCollectionField.class);
assertNotNull(target); assertThat(target).isNotNull();
assertTrue(target.children.isEmpty()); assertThat(target.children).isEmpty();
} }
private static class ClassWithCollectionField { private static class ClassWithCollectionField {
@ -322,44 +313,44 @@ public class ObjectTest {
} }
@Test @Test
public void testPrimitiveArrayInAnObjectDeserialization() throws Exception { public void testPrimitiveArrayInAnObjectDeserialization() {
String json = "{\"longArray\":[0,1,2,3,4,5,6,7,8,9]}"; String json = "{\"longArray\":[0,1,2,3,4,5,6,7,8,9]}";
PrimitiveArray target = gson.fromJson(json, PrimitiveArray.class); PrimitiveArray target = gson.fromJson(json, PrimitiveArray.class);
assertEquals(json, target.getExpectedJson()); assertThat(target.getExpectedJson()).isEqualTo(json);
} }
/** /**
* Created in response to Issue 14: http://code.google.com/p/google-gson/issues/detail?id=14 * Created in response to Issue 14: http://code.google.com/p/google-gson/issues/detail?id=14
*/ */
@Test @Test
public void testNullPrimitiveFieldsDeserialization() throws Exception { public void testNullPrimitiveFieldsDeserialization() {
String json = "{\"longValue\":null}"; String json = "{\"longValue\":null}";
BagOfPrimitives target = gson.fromJson(json, BagOfPrimitives.class); BagOfPrimitives target = gson.fromJson(json, BagOfPrimitives.class);
assertEquals(BagOfPrimitives.DEFAULT_VALUE, target.longValue); assertThat(target.longValue).isEqualTo(BagOfPrimitives.DEFAULT_VALUE);
} }
@Test @Test
public void testEmptyCollectionInAnObjectSerialization() throws Exception { public void testEmptyCollectionInAnObjectSerialization() {
ClassWithCollectionField target = new ClassWithCollectionField(); ClassWithCollectionField target = new ClassWithCollectionField();
assertEquals("{\"children\":[]}", gson.toJson(target)); assertThat(gson.toJson(target)).isEqualTo("{\"children\":[]}");
} }
@Test @Test
public void testPrivateNoArgConstructorDeserialization() throws Exception { public void testPrivateNoArgConstructorDeserialization() {
ClassWithPrivateNoArgsConstructor target = ClassWithPrivateNoArgsConstructor target =
gson.fromJson("{\"a\":20}", ClassWithPrivateNoArgsConstructor.class); gson.fromJson("{\"a\":20}", ClassWithPrivateNoArgsConstructor.class);
assertEquals(20, target.a); assertThat(target.a).isEqualTo(20);
} }
@Test @Test
public void testAnonymousLocalClassesSerialization() throws Exception { public void testAnonymousLocalClassesSerialization() {
assertEquals("null", gson.toJson(new ClassWithNoFields() { assertThat(gson.toJson(new ClassWithNoFields() {
// empty anonymous class // empty anonymous class
})); })).isEqualTo("null");
} }
@Test @Test
public void testAnonymousLocalClassesCustomSerialization() throws Exception { public void testAnonymousLocalClassesCustomSerialization() {
gson = new GsonBuilder() gson = new GsonBuilder()
.registerTypeHierarchyAdapter(ClassWithNoFields.class, .registerTypeHierarchyAdapter(ClassWithNoFields.class,
new JsonSerializer<ClassWithNoFields>() { new JsonSerializer<ClassWithNoFields>() {
@ -369,15 +360,15 @@ public class ObjectTest {
} }
}).create(); }).create();
assertEquals("null", gson.toJson(new ClassWithNoFields() { assertThat(gson.toJson(new ClassWithNoFields() {
// empty anonymous class // empty anonymous class
})); })).isEqualTo("null");
} }
@Test @Test
public void testPrimitiveArrayFieldSerialization() { public void testPrimitiveArrayFieldSerialization() {
PrimitiveArray target = new PrimitiveArray(new long[] { 1L, 2L, 3L }); PrimitiveArray target = new PrimitiveArray(new long[] { 1L, 2L, 3L });
assertEquals(target.getExpectedJson(), gson.toJson(target)); assertThat(gson.toJson(target)).isEqualTo(target.getExpectedJson());
} }
/** /**
@ -389,7 +380,7 @@ public class ObjectTest {
ClassWithObjectField obj = new ClassWithObjectField(); ClassWithObjectField obj = new ClassWithObjectField();
obj.member = "abc"; obj.member = "abc";
String json = gson.toJson(obj); String json = gson.toJson(obj);
assertTrue(json.contains("abc")); assertThat(json).contains("abc");
} }
private static class ClassWithObjectField { private static class ClassWithObjectField {
@ -402,8 +393,8 @@ public class ObjectTest {
Parent p = new Parent(); Parent p = new Parent();
Parent.Child c = p.new Child(); Parent.Child c = p.new Child();
String json = gson.toJson(c); String json = gson.toJson(c);
assertTrue(json.contains("value2")); assertThat(json).contains("value2");
assertFalse(json.contains("value1")); assertThat(json).doesNotContain("value1");
} }
@Test @Test
@ -417,7 +408,7 @@ public class ObjectTest {
}).create(); }).create();
String json = "{'value2':3}"; String json = "{'value2':3}";
Parent.Child c = gson.fromJson(json, Parent.Child.class); Parent.Child c = gson.fromJson(json, Parent.Child.class);
assertEquals(3, c.value2); assertThat(c.value2).isEqualTo(3);
} }
private static class Parent { private static class Parent {
@ -479,24 +470,24 @@ public class ObjectTest {
public void testObjectFieldNamesWithoutQuotesDeserialization() { public void testObjectFieldNamesWithoutQuotesDeserialization() {
String json = "{longValue:1,'booleanValue':true,\"stringValue\":'bar'}"; String json = "{longValue:1,'booleanValue':true,\"stringValue\":'bar'}";
BagOfPrimitives bag = gson.fromJson(json, BagOfPrimitives.class); BagOfPrimitives bag = gson.fromJson(json, BagOfPrimitives.class);
assertEquals(1, bag.longValue); assertThat(bag.longValue).isEqualTo(1);
assertTrue(bag.booleanValue); assertThat(bag.booleanValue).isTrue();
assertEquals("bar", bag.stringValue); assertThat(bag.stringValue).isEqualTo("bar");
} }
@Test @Test
public void testStringFieldWithNumberValueDeserialization() { public void testStringFieldWithNumberValueDeserialization() {
String json = "{\"stringValue\":1}"; String json = "{\"stringValue\":1}";
BagOfPrimitives bag = gson.fromJson(json, BagOfPrimitives.class); BagOfPrimitives bag = gson.fromJson(json, BagOfPrimitives.class);
assertEquals("1", bag.stringValue); assertThat(bag.stringValue).isEqualTo("1");
json = "{\"stringValue\":1.5E+6}"; json = "{\"stringValue\":1.5E+6}";
bag = gson.fromJson(json, BagOfPrimitives.class); bag = gson.fromJson(json, BagOfPrimitives.class);
assertEquals("1.5E+6", bag.stringValue); assertThat(bag.stringValue).isEqualTo("1.5E+6");
json = "{\"stringValue\":true}"; json = "{\"stringValue\":true}";
bag = gson.fromJson(json, BagOfPrimitives.class); bag = gson.fromJson(json, BagOfPrimitives.class);
assertEquals("true", bag.stringValue); assertThat(bag.stringValue).isEqualTo("true");
} }
/** /**
@ -507,9 +498,9 @@ public class ObjectTest {
ClassWithEmptyStringFields target = new ClassWithEmptyStringFields(); ClassWithEmptyStringFields target = new ClassWithEmptyStringFields();
target.a = "5794749"; target.a = "5794749";
String json = gson.toJson(target); String json = gson.toJson(target);
assertTrue(json.contains("\"a\":\"5794749\"")); assertThat(json).contains("\"a\":\"5794749\"");
assertTrue(json.contains("\"b\":\"\"")); assertThat(json).contains("\"b\":\"\"");
assertTrue(json.contains("\"c\":\"\"")); assertThat(json).contains("\"c\":\"\"");
} }
/** /**
@ -519,9 +510,9 @@ public class ObjectTest {
public void testStringFieldWithEmptyValueDeserialization() { public void testStringFieldWithEmptyValueDeserialization() {
String json = "{a:\"5794749\",b:\"\",c:\"\"}"; String json = "{a:\"5794749\",b:\"\",c:\"\"}";
ClassWithEmptyStringFields target = gson.fromJson(json, ClassWithEmptyStringFields.class); ClassWithEmptyStringFields target = gson.fromJson(json, ClassWithEmptyStringFields.class);
assertEquals("5794749", target.a); assertThat(target.a).isEqualTo("5794749");
assertEquals("", target.b); assertThat(target.b).isEqualTo("");
assertEquals("", target.c); assertThat(target.c).isEqualTo("");
} }
private static class ClassWithEmptyStringFields { private static class ClassWithEmptyStringFields {
@ -535,7 +526,7 @@ public class ObjectTest {
Gson gson = new GsonBuilder().serializeNulls().create(); Gson gson = new GsonBuilder().serializeNulls().create();
JsonObject obj = new JsonObject(); JsonObject obj = new JsonObject();
String json = gson.toJson(obj); String json = gson.toJson(obj);
assertEquals("{}", json); assertThat(json).isEqualTo("{}");
} }
/** /**
@ -545,18 +536,17 @@ public class ObjectTest {
public void testSingletonLists() { public void testSingletonLists() {
Gson gson = new Gson(); Gson gson = new Gson();
Product product = new Product(); Product product = new Product();
assertEquals("{\"attributes\":[],\"departments\":[]}", assertThat(gson.toJson(product)).isEqualTo("{\"attributes\":[],\"departments\":[]}");
gson.toJson(product));
gson.fromJson(gson.toJson(product), Product.class); gson.fromJson(gson.toJson(product), Product.class);
product.departments.add(new Department()); product.departments.add(new Department());
assertEquals("{\"attributes\":[],\"departments\":[{\"name\":\"abc\",\"code\":\"123\"}]}", assertThat(gson.toJson(product))
gson.toJson(product)); .isEqualTo("{\"attributes\":[],\"departments\":[{\"name\":\"abc\",\"code\":\"123\"}]}");
gson.fromJson(gson.toJson(product), Product.class); gson.fromJson(gson.toJson(product), Product.class);
product.attributes.add("456"); product.attributes.add("456");
assertEquals("{\"attributes\":[\"456\"],\"departments\":[{\"name\":\"abc\",\"code\":\"123\"}]}", assertThat(gson.toJson(product))
gson.toJson(product)); .isEqualTo("{\"attributes\":[\"456\"],\"departments\":[{\"name\":\"abc\",\"code\":\"123\"}]}");
gson.fromJson(gson.toJson(product), Product.class); gson.fromJson(gson.toJson(product), Product.class);
} }
@ -576,9 +566,9 @@ public class ObjectTest {
HasObjectMap a = new HasObjectMap(); HasObjectMap a = new HasObjectMap();
a.map.put("date", new Date(0)); a.map.put("date", new Date(0));
if (JavaVersion.isJava9OrLater()) { if (JavaVersion.isJava9OrLater()) {
assertEquals("{\"map\":{\"date\":\"Dec 31, 1969, 4:00:00 PM\"}}", gson.toJson(a)); assertThat(gson.toJson(a)).isEqualTo("{\"map\":{\"date\":\"Dec 31, 1969, 4:00:00 PM\"}}");
} else { } else {
assertEquals("{\"map\":{\"date\":\"Dec 31, 1969 4:00:00 PM\"}}", gson.toJson(a)); assertThat(gson.toJson(a)).isEqualTo("{\"map\":{\"date\":\"Dec 31, 1969 4:00:00 PM\"}}");
} }
} }
@ -595,7 +585,7 @@ public class ObjectTest {
@Test @Test
public void testStaticFieldSerialization() { public void testStaticFieldSerialization() {
// By default Gson should ignore static fields // By default Gson should ignore static fields
assertEquals("{}", gson.toJson(new ClassWithStaticField())); assertThat(gson.toJson(new ClassWithStaticField())).isEqualTo("{}");
Gson gson = new GsonBuilder() Gson gson = new GsonBuilder()
// Include static fields // Include static fields
@ -603,10 +593,10 @@ public class ObjectTest {
.create(); .create();
String json = gson.toJson(new ClassWithStaticField()); String json = gson.toJson(new ClassWithStaticField());
assertEquals("{\"s\":\"initial\"}", json); assertThat(json).isEqualTo("{\"s\":\"initial\"}");
json = gson.toJson(new ClassWithStaticFinalField()); json = gson.toJson(new ClassWithStaticFinalField());
assertEquals("{\"s\":\"initial\"}", json); assertThat(json).isEqualTo("{\"s\":\"initial\"}");
} }
/** /**
@ -619,7 +609,7 @@ public class ObjectTest {
public void testStaticFieldDeserialization() { public void testStaticFieldDeserialization() {
// By default Gson should ignore static fields // By default Gson should ignore static fields
gson.fromJson("{\"s\":\"custom\"}", ClassWithStaticField.class); gson.fromJson("{\"s\":\"custom\"}", ClassWithStaticField.class);
assertEquals("initial", ClassWithStaticField.s); assertThat(ClassWithStaticField.s).isEqualTo("initial");
Gson gson = new GsonBuilder() Gson gson = new GsonBuilder()
// Include static fields // Include static fields
@ -629,8 +619,8 @@ public class ObjectTest {
String oldValue = ClassWithStaticField.s; String oldValue = ClassWithStaticField.s;
try { try {
ClassWithStaticField obj = gson.fromJson("{\"s\":\"custom\"}", ClassWithStaticField.class); ClassWithStaticField obj = gson.fromJson("{\"s\":\"custom\"}", ClassWithStaticField.class);
assertNotNull(obj); assertThat(obj).isNotNull();
assertEquals("custom", ClassWithStaticField.s); assertThat(ClassWithStaticField.s).isEqualTo("custom");
} finally { } finally {
ClassWithStaticField.s = oldValue; ClassWithStaticField.s = oldValue;
} }
@ -639,8 +629,7 @@ public class ObjectTest {
gson.fromJson("{\"s\":\"custom\"}", ClassWithStaticFinalField.class); gson.fromJson("{\"s\":\"custom\"}", ClassWithStaticFinalField.class);
fail(); fail();
} catch (JsonIOException e) { } catch (JsonIOException e) {
assertEquals("Cannot set value of 'static final' field 'com.google.gson.functional.ObjectTest$ClassWithStaticFinalField#s'", assertThat( e.getMessage()).isEqualTo("Cannot set value of 'static final' field 'com.google.gson.functional.ObjectTest$ClassWithStaticFinalField#s'");
e.getMessage());
} }
} }
@ -660,9 +649,8 @@ public class ObjectTest {
} }
// TODO: Adjust this once Gson throws more specific exception type // TODO: Adjust this once Gson throws more specific exception type
catch (RuntimeException e) { catch (RuntimeException e) {
assertEquals("Failed to invoke constructor 'com.google.gson.functional.ObjectTest$ClassWithThrowingConstructor()' with no args", assertThat( e.getMessage()).isEqualTo("Failed to invoke constructor 'com.google.gson.functional.ObjectTest$ClassWithThrowingConstructor()' with no args");
e.getMessage()); assertThat(e).hasCauseThat().isSameInstanceAs(ClassWithThrowingConstructor.thrownException);
assertSame(ClassWithThrowingConstructor.thrownException, e.getCause());
} }
} }

View File

@ -16,8 +16,7 @@
package com.google.gson.functional; package com.google.gson.functional;
import static org.junit.Assert.assertEquals; import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertTrue;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;
@ -56,15 +55,15 @@ public class ParameterizedTypesTest {
} }
@Test @Test
public void testParameterizedTypesSerialization() throws Exception { public void testParameterizedTypesSerialization() {
MyParameterizedType<Integer> src = new MyParameterizedType<>(10); MyParameterizedType<Integer> src = new MyParameterizedType<>(10);
Type typeOfSrc = new TypeToken<MyParameterizedType<Integer>>() {}.getType(); Type typeOfSrc = new TypeToken<MyParameterizedType<Integer>>() {}.getType();
String json = gson.toJson(src, typeOfSrc); String json = gson.toJson(src, typeOfSrc);
assertEquals(src.getExpectedJson(), json); assertThat(json).isEqualTo(src.getExpectedJson());
} }
@Test @Test
public void testParameterizedTypeDeserialization() throws Exception { public void testParameterizedTypeDeserialization() {
BagOfPrimitives bag = new BagOfPrimitives(); BagOfPrimitives bag = new BagOfPrimitives();
MyParameterizedType<BagOfPrimitives> expected = new MyParameterizedType<>(bag); MyParameterizedType<BagOfPrimitives> expected = new MyParameterizedType<>(bag);
Type expectedType = new TypeToken<MyParameterizedType<BagOfPrimitives>>() {}.getType(); Type expectedType = new TypeToken<MyParameterizedType<BagOfPrimitives>>() {}.getType();
@ -75,11 +74,11 @@ public class ParameterizedTypesTest {
String json = expected.getExpectedJson(); String json = expected.getExpectedJson();
MyParameterizedType<BagOfPrimitives> actual = gson.fromJson(json, expectedType); MyParameterizedType<BagOfPrimitives> actual = gson.fromJson(json, expectedType);
assertEquals(expected, actual); assertThat(actual).isEqualTo(expected);
} }
@Test @Test
public void testTypesWithMultipleParametersSerialization() throws Exception { public void testTypesWithMultipleParametersSerialization() {
MultiParameters<Integer, Float, Double, String, BagOfPrimitives> src = MultiParameters<Integer, Float, Double, String, BagOfPrimitives> src =
new MultiParameters<>(10, 1.0F, 2.1D, "abc", new BagOfPrimitives()); new MultiParameters<>(10, 1.0F, 2.1D, "abc", new BagOfPrimitives());
Type typeOfSrc = new TypeToken<MultiParameters<Integer, Float, Double, String, Type typeOfSrc = new TypeToken<MultiParameters<Integer, Float, Double, String,
@ -87,11 +86,11 @@ public class ParameterizedTypesTest {
String json = gson.toJson(src, typeOfSrc); String json = gson.toJson(src, typeOfSrc);
String expected = "{\"a\":10,\"b\":1.0,\"c\":2.1,\"d\":\"abc\"," String expected = "{\"a\":10,\"b\":1.0,\"c\":2.1,\"d\":\"abc\","
+ "\"e\":{\"longValue\":0,\"intValue\":0,\"booleanValue\":false,\"stringValue\":\"\"}}"; + "\"e\":{\"longValue\":0,\"intValue\":0,\"booleanValue\":false,\"stringValue\":\"\"}}";
assertEquals(expected, json); assertThat(json).isEqualTo(expected);
} }
@Test @Test
public void testTypesWithMultipleParametersDeserialization() throws Exception { public void testTypesWithMultipleParametersDeserialization() {
Type typeOfTarget = new TypeToken<MultiParameters<Integer, Float, Double, String, Type typeOfTarget = new TypeToken<MultiParameters<Integer, Float, Double, String,
BagOfPrimitives>>() {}.getType(); BagOfPrimitives>>() {}.getType();
String json = "{\"a\":10,\"b\":1.0,\"c\":2.1,\"d\":\"abc\"," String json = "{\"a\":10,\"b\":1.0,\"c\":2.1,\"d\":\"abc\","
@ -100,7 +99,7 @@ public class ParameterizedTypesTest {
gson.fromJson(json, typeOfTarget); gson.fromJson(json, typeOfTarget);
MultiParameters<Integer, Float, Double, String, BagOfPrimitives> expected = MultiParameters<Integer, Float, Double, String, BagOfPrimitives> expected =
new MultiParameters<>(10, 1.0F, 2.1D, "abc", new BagOfPrimitives()); new MultiParameters<>(10, 1.0F, 2.1D, "abc", new BagOfPrimitives());
assertEquals(expected, target); assertThat(target).isEqualTo(expected);
} }
@Test @Test
@ -113,11 +112,11 @@ public class ParameterizedTypesTest {
.create(); .create();
MyParameterizedType<Integer> intTarget = new MyParameterizedType<>(10); MyParameterizedType<Integer> intTarget = new MyParameterizedType<>(10);
String json = gson.toJson(intTarget, ptIntegerType); String json = gson.toJson(intTarget, ptIntegerType);
assertEquals(MyParameterizedTypeAdapter.<Integer>getExpectedJson(intTarget), json); assertThat(json).isEqualTo(MyParameterizedTypeAdapter.<Integer>getExpectedJson(intTarget));
MyParameterizedType<String> stringTarget = new MyParameterizedType<>("abc"); MyParameterizedType<String> stringTarget = new MyParameterizedType<>("abc");
json = gson.toJson(stringTarget, ptStringType); json = gson.toJson(stringTarget, ptStringType);
assertEquals(MyParameterizedTypeAdapter.<String>getExpectedJson(stringTarget), json); assertThat(json).isEqualTo(MyParameterizedTypeAdapter.<String>getExpectedJson(stringTarget));
} }
@Test @Test
@ -134,25 +133,25 @@ public class ParameterizedTypesTest {
MyParameterizedType<Integer> src = new MyParameterizedType<>(10); MyParameterizedType<Integer> src = new MyParameterizedType<>(10);
String json = MyParameterizedTypeAdapter.<Integer>getExpectedJson(src); String json = MyParameterizedTypeAdapter.<Integer>getExpectedJson(src);
MyParameterizedType<Integer> intTarget = gson.fromJson(json, ptIntegerType); MyParameterizedType<Integer> intTarget = gson.fromJson(json, ptIntegerType);
assertEquals(10, intTarget.value.intValue()); assertThat(intTarget.value).isEqualTo(10);
MyParameterizedType<String> srcStr = new MyParameterizedType<>("abc"); MyParameterizedType<String> srcStr = new MyParameterizedType<>("abc");
json = MyParameterizedTypeAdapter.<String>getExpectedJson(srcStr); json = MyParameterizedTypeAdapter.<String>getExpectedJson(srcStr);
MyParameterizedType<String> stringTarget = gson.fromJson(json, ptStringType); MyParameterizedType<String> stringTarget = gson.fromJson(json, ptStringType);
assertEquals("abc", stringTarget.value); assertThat(stringTarget.value).isEqualTo("abc");
} }
@Test @Test
public void testParameterizedTypesWithWriterSerialization() throws Exception { public void testParameterizedTypesWithWriterSerialization() {
Writer writer = new StringWriter(); Writer writer = new StringWriter();
MyParameterizedType<Integer> src = new MyParameterizedType<>(10); MyParameterizedType<Integer> src = new MyParameterizedType<>(10);
Type typeOfSrc = new TypeToken<MyParameterizedType<Integer>>() {}.getType(); Type typeOfSrc = new TypeToken<MyParameterizedType<Integer>>() {}.getType();
gson.toJson(src, typeOfSrc, writer); gson.toJson(src, typeOfSrc, writer);
assertEquals(src.getExpectedJson(), writer.toString()); assertThat(writer.toString()).isEqualTo(src.getExpectedJson());
} }
@Test @Test
public void testParameterizedTypeWithReaderDeserialization() throws Exception { public void testParameterizedTypeWithReaderDeserialization() {
BagOfPrimitives bag = new BagOfPrimitives(); BagOfPrimitives bag = new BagOfPrimitives();
MyParameterizedType<BagOfPrimitives> expected = new MyParameterizedType<>(bag); MyParameterizedType<BagOfPrimitives> expected = new MyParameterizedType<>(bag);
Type expectedType = new TypeToken<MyParameterizedType<BagOfPrimitives>>() {}.getType(); Type expectedType = new TypeToken<MyParameterizedType<BagOfPrimitives>>() {}.getType();
@ -163,7 +162,7 @@ public class ParameterizedTypesTest {
Reader json = new StringReader(expected.getExpectedJson()); Reader json = new StringReader(expected.getExpectedJson());
MyParameterizedType<Integer> actual = gson.fromJson(json, expectedType); MyParameterizedType<Integer> actual = gson.fromJson(json, expectedType);
assertEquals(expected, actual); assertThat(actual).isEqualTo(expected);
} }
@SuppressWarnings("varargs") @SuppressWarnings("varargs")
@ -173,7 +172,7 @@ public class ParameterizedTypesTest {
} }
@Test @Test
public void testVariableTypeFieldsAndGenericArraysSerialization() throws Exception { public void testVariableTypeFieldsAndGenericArraysSerialization() {
Integer obj = 0; Integer obj = 0;
Integer[] array = { 1, 2, 3 }; Integer[] array = { 1, 2, 3 };
List<Integer> list = new ArrayList<>(); List<Integer> list = new ArrayList<>();
@ -186,11 +185,11 @@ public class ParameterizedTypesTest {
new ObjectWithTypeVariables<>(obj, array, list, arrayOfLists, list, arrayOfLists); new ObjectWithTypeVariables<>(obj, array, list, arrayOfLists, list, arrayOfLists);
String json = gson.toJson(objToSerialize, typeOfSrc); String json = gson.toJson(objToSerialize, typeOfSrc);
assertEquals(objToSerialize.getExpectedJson(), json); assertThat(json).isEqualTo(objToSerialize.getExpectedJson());
} }
@Test @Test
public void testVariableTypeFieldsAndGenericArraysDeserialization() throws Exception { public void testVariableTypeFieldsAndGenericArraysDeserialization() {
Integer obj = 0; Integer obj = 0;
Integer[] array = { 1, 2, 3 }; Integer[] array = { 1, 2, 3 };
List<Integer> list = new ArrayList<>(); List<Integer> list = new ArrayList<>();
@ -204,22 +203,22 @@ public class ParameterizedTypesTest {
String json = gson.toJson(objToSerialize, typeOfSrc); String json = gson.toJson(objToSerialize, typeOfSrc);
ObjectWithTypeVariables<Integer> objAfterDeserialization = gson.fromJson(json, typeOfSrc); ObjectWithTypeVariables<Integer> objAfterDeserialization = gson.fromJson(json, typeOfSrc);
assertEquals(objAfterDeserialization.getExpectedJson(), json); assertThat(json).isEqualTo(objAfterDeserialization.getExpectedJson());
} }
@Test @Test
public void testVariableTypeDeserialization() throws Exception { public void testVariableTypeDeserialization() {
Type typeOfSrc = new TypeToken<ObjectWithTypeVariables<Integer>>() {}.getType(); Type typeOfSrc = new TypeToken<ObjectWithTypeVariables<Integer>>() {}.getType();
ObjectWithTypeVariables<Integer> objToSerialize = ObjectWithTypeVariables<Integer> objToSerialize =
new ObjectWithTypeVariables<>(0, null, null, null, null, null); new ObjectWithTypeVariables<>(0, null, null, null, null, null);
String json = gson.toJson(objToSerialize, typeOfSrc); String json = gson.toJson(objToSerialize, typeOfSrc);
ObjectWithTypeVariables<Integer> objAfterDeserialization = gson.fromJson(json, typeOfSrc); ObjectWithTypeVariables<Integer> objAfterDeserialization = gson.fromJson(json, typeOfSrc);
assertEquals(objAfterDeserialization.getExpectedJson(), json); assertThat(json).isEqualTo(objAfterDeserialization.getExpectedJson());
} }
@Test @Test
public void testVariableTypeArrayDeserialization() throws Exception { public void testVariableTypeArrayDeserialization() {
Integer[] array = { 1, 2, 3 }; Integer[] array = { 1, 2, 3 };
Type typeOfSrc = new TypeToken<ObjectWithTypeVariables<Integer>>() {}.getType(); Type typeOfSrc = new TypeToken<ObjectWithTypeVariables<Integer>>() {}.getType();
@ -228,11 +227,11 @@ public class ParameterizedTypesTest {
String json = gson.toJson(objToSerialize, typeOfSrc); String json = gson.toJson(objToSerialize, typeOfSrc);
ObjectWithTypeVariables<Integer> objAfterDeserialization = gson.fromJson(json, typeOfSrc); ObjectWithTypeVariables<Integer> objAfterDeserialization = gson.fromJson(json, typeOfSrc);
assertEquals(objAfterDeserialization.getExpectedJson(), json); assertThat(json).isEqualTo(objAfterDeserialization.getExpectedJson());
} }
@Test @Test
public void testParameterizedTypeWithVariableTypeDeserialization() throws Exception { public void testParameterizedTypeWithVariableTypeDeserialization() {
List<Integer> list = new ArrayList<>(); List<Integer> list = new ArrayList<>();
list.add(4); list.add(4);
list.add(5); list.add(5);
@ -243,11 +242,11 @@ public class ParameterizedTypesTest {
String json = gson.toJson(objToSerialize, typeOfSrc); String json = gson.toJson(objToSerialize, typeOfSrc);
ObjectWithTypeVariables<Integer> objAfterDeserialization = gson.fromJson(json, typeOfSrc); ObjectWithTypeVariables<Integer> objAfterDeserialization = gson.fromJson(json, typeOfSrc);
assertEquals(objAfterDeserialization.getExpectedJson(), json); assertThat(json).isEqualTo(objAfterDeserialization.getExpectedJson());
} }
@Test @Test
public void testParameterizedTypeGenericArraysSerialization() throws Exception { public void testParameterizedTypeGenericArraysSerialization() {
List<Integer> list = new ArrayList<>(); List<Integer> list = new ArrayList<>();
list.add(1); list.add(1);
list.add(2); list.add(2);
@ -257,11 +256,11 @@ public class ParameterizedTypesTest {
ObjectWithTypeVariables<Integer> objToSerialize = ObjectWithTypeVariables<Integer> objToSerialize =
new ObjectWithTypeVariables<>(null, null, null, arrayOfLists, null, null); new ObjectWithTypeVariables<>(null, null, null, arrayOfLists, null, null);
String json = gson.toJson(objToSerialize, typeOfSrc); String json = gson.toJson(objToSerialize, typeOfSrc);
assertEquals("{\"arrayOfListOfTypeParameters\":[[1,2],[1,2]]}", json); assertThat(json).isEqualTo("{\"arrayOfListOfTypeParameters\":[[1,2],[1,2]]}");
} }
@Test @Test
public void testParameterizedTypeGenericArraysDeserialization() throws Exception { public void testParameterizedTypeGenericArraysDeserialization() {
List<Integer> list = new ArrayList<>(); List<Integer> list = new ArrayList<>();
list.add(1); list.add(1);
list.add(2); list.add(2);
@ -273,7 +272,7 @@ public class ParameterizedTypesTest {
String json = gson.toJson(objToSerialize, typeOfSrc); String json = gson.toJson(objToSerialize, typeOfSrc);
ObjectWithTypeVariables<Integer> objAfterDeserialization = gson.fromJson(json, typeOfSrc); ObjectWithTypeVariables<Integer> objAfterDeserialization = gson.fromJson(json, typeOfSrc);
assertEquals(objAfterDeserialization.getExpectedJson(), json); assertThat(json).isEqualTo(objAfterDeserialization.getExpectedJson());
} }
/** /**
@ -508,8 +507,8 @@ public class ParameterizedTypesTest {
public void testDeepParameterizedTypeSerialization() { public void testDeepParameterizedTypeSerialization() {
Amount<MyQuantity> amount = new Amount<>(); Amount<MyQuantity> amount = new Amount<>();
String json = gson.toJson(amount); String json = gson.toJson(amount);
assertTrue(json.contains("value")); assertThat(json).contains("value");
assertTrue(json.contains("30")); assertThat(json).contains("30");
} }
@Test @Test
@ -517,15 +516,15 @@ public class ParameterizedTypesTest {
String json = "{value:30}"; String json = "{value:30}";
Type type = new TypeToken<Amount<MyQuantity>>() {}.getType(); Type type = new TypeToken<Amount<MyQuantity>>() {}.getType();
Amount<MyQuantity> amount = gson.fromJson(json, type); Amount<MyQuantity> amount = gson.fromJson(json, type);
assertEquals(30, amount.value); assertThat(amount.value).isEqualTo(30);
} }
// End: tests to reproduce issue 103 // End: tests to reproduce issue 103
private static void assertCorrectlyDeserialized(Object object) { private static void assertCorrectlyDeserialized(Object object) {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
List<Quantity> list = (List<Quantity>) object; List<Quantity> list = (List<Quantity>) object;
assertEquals(1, list.size()); assertThat(list.size()).isEqualTo(1);
assertEquals(4, list.get(0).q); assertThat(list.get(0).q).isEqualTo(4);
} }
@Test @Test

View File

@ -15,8 +15,7 @@
*/ */
package com.google.gson.functional; package com.google.gson.functional;
import static org.junit.Assert.assertEquals; import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertTrue;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;
@ -72,7 +71,7 @@ public class PrettyPrintingTest {
public void testPrettyPrintArrayOfPrimitives() { public void testPrettyPrintArrayOfPrimitives() {
int[] ints = new int[] { 1, 2, 3, 4, 5 }; int[] ints = new int[] { 1, 2, 3, 4, 5 };
String json = gson.toJson(ints); String json = gson.toJson(ints);
assertEquals("[\n 1,\n 2,\n 3,\n 4,\n 5\n]", json); assertThat(json).isEqualTo("[\n 1,\n 2,\n 3,\n 4,\n 5\n]");
} }
@Test @Test
@ -80,8 +79,8 @@ public class PrettyPrintingTest {
int[][] ints = new int[][] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 }, int[][] ints = new int[][] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 },
{ 9, 0 }, { 10 } }; { 9, 0 }, { 10 } };
String json = gson.toJson(ints); String json = gson.toJson(ints);
assertEquals("[\n [\n 1,\n 2\n ],\n [\n 3,\n 4\n ],\n [\n 5,\n 6\n ]," assertThat(json).isEqualTo("[\n [\n 1,\n 2\n ],\n [\n 3,\n 4\n ],\n [\n 5,\n 6\n ],"
+ "\n [\n 7,\n 8\n ],\n [\n 9,\n 0\n ],\n [\n 10\n ]\n]", json); + "\n [\n 7,\n 8\n ],\n [\n 9,\n 0\n ],\n [\n 10\n ]\n]");
} }
@Test @Test
@ -89,8 +88,8 @@ public class PrettyPrintingTest {
List<Integer[]> list = Arrays.asList(new Integer[][] { { 1, 2 }, { 3, 4 }, List<Integer[]> list = Arrays.asList(new Integer[][] { { 1, 2 }, { 3, 4 },
{ 5, 6 }, { 7, 8 }, { 9, 0 }, { 10 } }); { 5, 6 }, { 7, 8 }, { 9, 0 }, { 10 } });
String json = gson.toJson(list); String json = gson.toJson(list);
assertEquals("[\n [\n 1,\n 2\n ],\n [\n 3,\n 4\n ],\n [\n 5,\n 6\n ]," assertThat(json).isEqualTo("[\n [\n 1,\n 2\n ],\n [\n 3,\n 4\n ],\n [\n 5,\n 6\n ],"
+ "\n [\n 7,\n 8\n ],\n [\n 9,\n 0\n ],\n [\n 10\n ]\n]", json); + "\n [\n 7,\n 8\n ],\n [\n 9,\n 0\n ],\n [\n 10\n ]\n]");
} }
@Test @Test
@ -99,7 +98,7 @@ public class PrettyPrintingTest {
map.put("abc", 1); map.put("abc", 1);
map.put("def", 5); map.put("def", 5);
String json = gson.toJson(map); String json = gson.toJson(map);
assertEquals("{\n \"abc\": 1,\n \"def\": 5\n}", json); assertThat(json).isEqualTo("{\n \"abc\": 1,\n \"def\": 5\n}");
} }
// In response to bug 153 // In response to bug 153
@ -108,7 +107,7 @@ public class PrettyPrintingTest {
ClassWithMap obj = new ClassWithMap(); ClassWithMap obj = new ClassWithMap();
obj.map = new LinkedHashMap<>(); obj.map = new LinkedHashMap<>();
String json = gson.toJson(obj); String json = gson.toJson(obj);
assertTrue(json.contains("{\n \"map\": {},\n \"value\": 2\n}")); assertThat(json).contains("{\n \"map\": {},\n \"value\": 2\n}");
} }
@SuppressWarnings("unused") @SuppressWarnings("unused")
@ -121,7 +120,7 @@ public class PrettyPrintingTest {
public void testMultipleArrays() { public void testMultipleArrays() {
int[][][] ints = new int[][][] { { { 1 }, { 2 } } }; int[][][] ints = new int[][][] { { { 1 }, { 2 } } };
String json = gson.toJson(ints); String json = gson.toJson(ints);
assertEquals("[\n [\n [\n 1\n ],\n [\n 2\n ]\n ]\n]", json); assertThat(json).isEqualTo("[\n [\n [\n 1\n ],\n [\n 2\n ]\n ]\n]");
} }
private void print(String msg) { private void print(String msg) {

View File

@ -16,7 +16,7 @@
package com.google.gson.functional; 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.Gson;
import org.junit.Before; import org.junit.Before;
@ -38,21 +38,21 @@ public class PrimitiveCharacterTest {
@Test @Test
public void testPrimitiveCharacterAutoboxedSerialization() { public void testPrimitiveCharacterAutoboxedSerialization() {
assertEquals("\"A\"", gson.toJson('A')); assertThat(gson.toJson('A')).isEqualTo("\"A\"");
assertEquals("\"A\"", gson.toJson('A', char.class)); assertThat(gson.toJson('A', char.class)).isEqualTo("\"A\"");
assertEquals("\"A\"", gson.toJson('A', Character.class)); assertThat(gson.toJson('A', Character.class)).isEqualTo("\"A\"");
} }
@Test @Test
public void testPrimitiveCharacterAutoboxedDeserialization() { public void testPrimitiveCharacterAutoboxedDeserialization() {
char expected = 'a'; char expected = 'a';
char actual = gson.fromJson("a", char.class); char actual = gson.fromJson("a", char.class);
assertEquals(expected, actual); assertThat(actual).isEqualTo(expected);
actual = gson.fromJson("\"a\"", char.class); actual = gson.fromJson("\"a\"", char.class);
assertEquals(expected, actual); assertThat(actual).isEqualTo(expected);
actual = gson.fromJson("a", Character.class); actual = gson.fromJson("a", Character.class);
assertEquals(expected, actual); assertThat(actual).isEqualTo(expected);
} }
} }

View File

@ -16,10 +16,7 @@
package com.google.gson.functional; package com.google.gson.functional;
import static org.junit.Assert.assertArrayEquals; import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import com.google.gson.Gson; import com.google.gson.Gson;
@ -54,39 +51,39 @@ public class PrimitiveTest {
@Test @Test
public void testPrimitiveIntegerAutoboxedSerialization() { public void testPrimitiveIntegerAutoboxedSerialization() {
assertEquals("1", gson.toJson(1)); assertThat(gson.toJson(1)).isEqualTo("1");
} }
@Test @Test
public void testPrimitiveIntegerAutoboxedDeserialization() { public void testPrimitiveIntegerAutoboxedDeserialization() {
int expected = 1; int expected = 1;
int actual = gson.fromJson("1", int.class); int actual = gson.fromJson("1", int.class);
assertEquals(expected, actual); assertThat(actual).isEqualTo(expected);
actual = gson.fromJson("1", Integer.class); actual = gson.fromJson("1", Integer.class);
assertEquals(expected, actual); assertThat(actual).isEqualTo(expected);
} }
@Test @Test
public void testByteSerialization() { public void testByteSerialization() {
assertEquals("1", gson.toJson(1, byte.class)); assertThat(gson.toJson(1, byte.class)).isEqualTo("1");
assertEquals("1", gson.toJson(1, Byte.class)); assertThat(gson.toJson(1, Byte.class)).isEqualTo("1");
assertEquals(Byte.toString(Byte.MIN_VALUE), gson.toJson(Byte.MIN_VALUE, Byte.class)); assertThat(gson.toJson(Byte.MIN_VALUE, Byte.class)).isEqualTo(Byte.toString(Byte.MIN_VALUE));
assertEquals(Byte.toString(Byte.MAX_VALUE), gson.toJson(Byte.MAX_VALUE, Byte.class)); assertThat(gson.toJson(Byte.MAX_VALUE, Byte.class)).isEqualTo(Byte.toString(Byte.MAX_VALUE));
// Should perform narrowing conversion // Should perform narrowing conversion
assertEquals("-128", gson.toJson(128, Byte.class)); assertThat(gson.toJson(128, Byte.class)).isEqualTo("-128");
assertEquals("1", gson.toJson(1.5, Byte.class)); assertThat(gson.toJson(1.5, Byte.class)).isEqualTo("1");
} }
@Test @Test
public void testByteDeserialization() { public void testByteDeserialization() {
Byte boxed = gson.fromJson("1", Byte.class); Byte boxed = gson.fromJson("1", Byte.class);
assertEquals(1, (byte)boxed); assertThat(boxed).isEqualTo(1);
byte primitive = gson.fromJson("1", byte.class); byte primitive = gson.fromJson("1", byte.class);
assertEquals(1, primitive); assertThat(primitive).isEqualTo(1);
byte[] bytes = gson.fromJson("[-128, 0, 127, 255]", byte[].class); byte[] bytes = gson.fromJson("[-128, 0, 127, 255]", byte[].class);
assertArrayEquals(new byte[] {-128, 0, 127, -1}, bytes); assertThat(bytes).isEqualTo(new byte[] {-128, 0, 127, -1});
} }
@Test @Test
@ -95,46 +92,46 @@ public class PrimitiveTest {
gson.fromJson("-129", byte.class); gson.fromJson("-129", byte.class);
fail(); fail();
} catch (JsonSyntaxException e) { } catch (JsonSyntaxException e) {
assertEquals("Lossy conversion from -129 to byte; at path $", e.getMessage()); assertThat(e.getMessage()).isEqualTo("Lossy conversion from -129 to byte; at path $");
} }
try { try {
gson.fromJson("256", byte.class); gson.fromJson("256", byte.class);
fail(); fail();
} catch (JsonSyntaxException e) { } catch (JsonSyntaxException e) {
assertEquals("Lossy conversion from 256 to byte; at path $", e.getMessage()); assertThat(e.getMessage()).isEqualTo("Lossy conversion from 256 to byte; at path $");
} }
try { try {
gson.fromJson("2147483648", byte.class); gson.fromJson("2147483648", byte.class);
fail(); fail();
} catch (JsonSyntaxException e) { } catch (JsonSyntaxException e) {
assertEquals("java.lang.NumberFormatException: Expected an int but was 2147483648 at line 1 column 11 path $", e.getMessage()); assertThat(e.getMessage()).isEqualTo("java.lang.NumberFormatException: Expected an int but was 2147483648 at line 1 column 11 path $");
} }
} }
@Test @Test
public void testShortSerialization() { public void testShortSerialization() {
assertEquals("1", gson.toJson(1, short.class)); assertThat(gson.toJson(1, short.class)).isEqualTo("1");
assertEquals("1", gson.toJson(1, Short.class)); assertThat(gson.toJson(1, Short.class)).isEqualTo("1");
assertEquals(Short.toString(Short.MIN_VALUE), gson.toJson(Short.MIN_VALUE, Short.class)); assertThat(gson.toJson(Short.MIN_VALUE, Short.class)).isEqualTo(Short.toString(Short.MIN_VALUE));
assertEquals(Short.toString(Short.MAX_VALUE), gson.toJson(Short.MAX_VALUE, Short.class)); assertThat(gson.toJson(Short.MAX_VALUE, Short.class)).isEqualTo(Short.toString(Short.MAX_VALUE));
// Should perform widening conversion // Should perform widening conversion
assertEquals("1", gson.toJson((byte) 1, Short.class)); assertThat(gson.toJson((byte) 1, Short.class)).isEqualTo("1");
// Should perform narrowing conversion // Should perform narrowing conversion
assertEquals("-32768", gson.toJson(32768, Short.class)); assertThat(gson.toJson(32768, Short.class)).isEqualTo("-32768");
assertEquals("1", gson.toJson(1.5, Short.class)); assertThat(gson.toJson(1.5, Short.class)).isEqualTo("1");
} }
@Test @Test
public void testShortDeserialization() { public void testShortDeserialization() {
Short boxed = gson.fromJson("1", Short.class); Short boxed = gson.fromJson("1", Short.class);
assertEquals(1, (short)boxed); assertThat(boxed).isEqualTo(1);
short primitive = gson.fromJson("1", short.class); short primitive = gson.fromJson("1", short.class);
assertEquals(1, primitive); assertThat(primitive).isEqualTo(1);
short[] shorts = gson.fromJson("[-32768, 0, 32767, 65535]", short[].class); short[] shorts = gson.fromJson("[-32768, 0, 32767, 65535]", short[].class);
assertArrayEquals(new short[] {-32768, 0, 32767, -1}, shorts); assertThat(shorts).isEqualTo(new short[] {-32768, 0, 32767, -1});
} }
@Test @Test
@ -143,151 +140,151 @@ public class PrimitiveTest {
gson.fromJson("-32769", short.class); gson.fromJson("-32769", short.class);
fail(); fail();
} catch (JsonSyntaxException e) { } catch (JsonSyntaxException e) {
assertEquals("Lossy conversion from -32769 to short; at path $", e.getMessage()); assertThat(e.getMessage()).isEqualTo("Lossy conversion from -32769 to short; at path $");
} }
try { try {
gson.fromJson("65536", short.class); gson.fromJson("65536", short.class);
fail(); fail();
} catch (JsonSyntaxException e) { } catch (JsonSyntaxException e) {
assertEquals("Lossy conversion from 65536 to short; at path $", e.getMessage()); assertThat(e.getMessage()).isEqualTo("Lossy conversion from 65536 to short; at path $");
} }
try { try {
gson.fromJson("2147483648", short.class); gson.fromJson("2147483648", short.class);
fail(); fail();
} catch (JsonSyntaxException e) { } catch (JsonSyntaxException e) {
assertEquals("java.lang.NumberFormatException: Expected an int but was 2147483648 at line 1 column 11 path $", e.getMessage()); assertThat(e.getMessage()).isEqualTo("java.lang.NumberFormatException: Expected an int but was 2147483648 at line 1 column 11 path $");
} }
} }
@Test @Test
public void testIntSerialization() { public void testIntSerialization() {
assertEquals("1", gson.toJson(1, int.class)); assertThat(gson.toJson(1, int.class)).isEqualTo("1");
assertEquals("1", gson.toJson(1, Integer.class)); assertThat(gson.toJson(1, Integer.class)).isEqualTo("1");
assertEquals(Integer.toString(Integer.MIN_VALUE), gson.toJson(Integer.MIN_VALUE, Integer.class)); assertThat(gson.toJson(Integer.MIN_VALUE, Integer.class)).isEqualTo(Integer.toString(Integer.MIN_VALUE));
assertEquals(Integer.toString(Integer.MAX_VALUE), gson.toJson(Integer.MAX_VALUE, Integer.class)); assertThat(gson.toJson(Integer.MAX_VALUE, Integer.class)).isEqualTo(Integer.toString(Integer.MAX_VALUE));
// Should perform widening conversion // Should perform widening conversion
assertEquals("1", gson.toJson((byte) 1, Integer.class)); assertThat(gson.toJson((byte) 1, Integer.class)).isEqualTo("1");
// Should perform narrowing conversion // Should perform narrowing conversion
assertEquals("-2147483648", gson.toJson(2147483648L, Integer.class)); assertThat(gson.toJson(2147483648L, Integer.class)).isEqualTo("-2147483648");
assertEquals("1", gson.toJson(1.5, Integer.class)); assertThat(gson.toJson(1.5, Integer.class)).isEqualTo("1");
} }
@Test @Test
public void testLongSerialization() { public void testLongSerialization() {
assertEquals("1", gson.toJson(1L, long.class)); assertThat(gson.toJson(1L, long.class)).isEqualTo("1");
assertEquals("1", gson.toJson(1L, Long.class)); assertThat(gson.toJson(1L, Long.class)).isEqualTo("1");
assertEquals(Long.toString(Long.MIN_VALUE), gson.toJson(Long.MIN_VALUE, Long.class)); assertThat(gson.toJson(Long.MIN_VALUE, Long.class)).isEqualTo(Long.toString(Long.MIN_VALUE));
assertEquals(Long.toString(Long.MAX_VALUE), gson.toJson(Long.MAX_VALUE, Long.class)); assertThat(gson.toJson(Long.MAX_VALUE, Long.class)).isEqualTo(Long.toString(Long.MAX_VALUE));
// Should perform widening conversion // Should perform widening conversion
assertEquals("1", gson.toJson((byte) 1, Long.class)); assertThat(gson.toJson((byte) 1, Long.class)).isEqualTo("1");
// Should perform narrowing conversion // Should perform narrowing conversion
assertEquals("1", gson.toJson(1.5, Long.class)); assertThat(gson.toJson(1.5, Long.class)).isEqualTo("1");
} }
@Test @Test
public void testFloatSerialization() { public void testFloatSerialization() {
assertEquals("1.5", gson.toJson(1.5f, float.class)); assertThat(gson.toJson(1.5f, float.class)).isEqualTo("1.5");
assertEquals("1.5", gson.toJson(1.5f, Float.class)); assertThat(gson.toJson(1.5f, Float.class)).isEqualTo("1.5");
assertEquals(Float.toString(Float.MIN_VALUE), gson.toJson(Float.MIN_VALUE, Float.class)); assertThat(gson.toJson(Float.MIN_VALUE, Float.class)).isEqualTo(Float.toString(Float.MIN_VALUE));
assertEquals(Float.toString(Float.MAX_VALUE), gson.toJson(Float.MAX_VALUE, Float.class)); assertThat(gson.toJson(Float.MAX_VALUE, Float.class)).isEqualTo(Float.toString(Float.MAX_VALUE));
// Should perform widening conversion // Should perform widening conversion
assertEquals("1.0", gson.toJson((byte) 1, Float.class)); assertThat(gson.toJson((byte) 1, Float.class)).isEqualTo("1.0");
// (This widening conversion is actually lossy) // (This widening conversion is actually lossy)
assertEquals(Float.toString(Long.MAX_VALUE - 10L), gson.toJson(Long.MAX_VALUE - 10L, Float.class)); assertThat(gson.toJson(Long.MAX_VALUE - 10L, Float.class)).isEqualTo(Float.toString(Long.MAX_VALUE - 10L));
// Should perform narrowing conversion // Should perform narrowing conversion
gson = new GsonBuilder().serializeSpecialFloatingPointValues().create(); gson = new GsonBuilder().serializeSpecialFloatingPointValues().create();
assertEquals("Infinity", gson.toJson(Double.MAX_VALUE, Float.class)); assertThat(gson.toJson(Double.MAX_VALUE, Float.class)).isEqualTo("Infinity");
} }
@Test @Test
public void testDoubleSerialization() { public void testDoubleSerialization() {
assertEquals("1.5", gson.toJson(1.5, double.class)); assertThat(gson.toJson(1.5, double.class)).isEqualTo("1.5");
assertEquals("1.5", gson.toJson(1.5, Double.class)); assertThat(gson.toJson(1.5, Double.class)).isEqualTo("1.5");
assertEquals(Double.toString(Double.MIN_VALUE), gson.toJson(Double.MIN_VALUE, Double.class)); assertThat(gson.toJson(Double.MIN_VALUE, Double.class)).isEqualTo(Double.toString(Double.MIN_VALUE));
assertEquals(Double.toString(Double.MAX_VALUE), gson.toJson(Double.MAX_VALUE, Double.class)); assertThat(gson.toJson(Double.MAX_VALUE, Double.class)).isEqualTo(Double.toString(Double.MAX_VALUE));
// Should perform widening conversion // Should perform widening conversion
assertEquals("1.0", gson.toJson((byte) 1, Double.class)); assertThat(gson.toJson((byte) 1, Double.class)).isEqualTo("1.0");
// (This widening conversion is actually lossy) // (This widening conversion is actually lossy)
assertEquals(Double.toString(Long.MAX_VALUE - 10L), gson.toJson(Long.MAX_VALUE - 10L, Double.class)); assertThat(gson.toJson(Long.MAX_VALUE - 10L, Double.class)).isEqualTo(Double.toString(Long.MAX_VALUE - 10L));
} }
@Test @Test
public void testPrimitiveIntegerAutoboxedInASingleElementArraySerialization() { public void testPrimitiveIntegerAutoboxedInASingleElementArraySerialization() {
int target[] = {-9332}; int[] target = {-9332};
assertEquals("[-9332]", gson.toJson(target)); assertThat(gson.toJson(target)).isEqualTo("[-9332]");
assertEquals("[-9332]", gson.toJson(target, int[].class)); assertThat(gson.toJson(target, int[].class)).isEqualTo("[-9332]");
assertEquals("[-9332]", gson.toJson(target, Integer[].class)); assertThat(gson.toJson(target, Integer[].class)).isEqualTo("[-9332]");
} }
@Test @Test
public void testReallyLongValuesSerialization() { public void testReallyLongValuesSerialization() {
long value = 333961828784581L; long value = 333961828784581L;
assertEquals("333961828784581", gson.toJson(value)); assertThat(gson.toJson(value)).isEqualTo("333961828784581");
} }
@Test @Test
public void testReallyLongValuesDeserialization() { public void testReallyLongValuesDeserialization() {
String json = "333961828784581"; String json = "333961828784581";
long value = gson.fromJson(json, Long.class); long value = gson.fromJson(json, Long.class);
assertEquals(333961828784581L, value); assertThat(value).isEqualTo(333961828784581L);
} }
@Test @Test
public void testPrimitiveLongAutoboxedSerialization() { public void testPrimitiveLongAutoboxedSerialization() {
assertEquals("1", gson.toJson(1L, long.class)); assertThat(gson.toJson(1L, long.class)).isEqualTo("1");
assertEquals("1", gson.toJson(1L, Long.class)); assertThat(gson.toJson(1L, Long.class)).isEqualTo("1");
} }
@Test @Test
public void testPrimitiveLongAutoboxedDeserialization() { public void testPrimitiveLongAutoboxedDeserialization() {
long expected = 1L; long expected = 1L;
long actual = gson.fromJson("1", long.class); long actual = gson.fromJson("1", long.class);
assertEquals(expected, actual); assertThat(actual).isEqualTo(expected);
actual = gson.fromJson("1", Long.class); actual = gson.fromJson("1", Long.class);
assertEquals(expected, actual); assertThat(actual).isEqualTo(expected);
} }
@Test @Test
public void testPrimitiveLongAutoboxedInASingleElementArraySerialization() { public void testPrimitiveLongAutoboxedInASingleElementArraySerialization() {
long[] target = {-23L}; long[] target = {-23L};
assertEquals("[-23]", gson.toJson(target)); assertThat(gson.toJson(target)).isEqualTo("[-23]");
assertEquals("[-23]", gson.toJson(target, long[].class)); assertThat(gson.toJson(target, long[].class)).isEqualTo("[-23]");
assertEquals("[-23]", gson.toJson(target, Long[].class)); assertThat(gson.toJson(target, Long[].class)).isEqualTo("[-23]");
} }
@Test @Test
public void testPrimitiveBooleanAutoboxedSerialization() { public void testPrimitiveBooleanAutoboxedSerialization() {
assertEquals("true", gson.toJson(true)); assertThat(gson.toJson(true)).isEqualTo("true");
assertEquals("false", gson.toJson(false)); assertThat(gson.toJson(false)).isEqualTo("false");
} }
@Test @Test
public void testBooleanDeserialization() { public void testBooleanDeserialization() {
boolean value = gson.fromJson("false", boolean.class); boolean value = gson.fromJson("false", boolean.class);
assertEquals(false, value); assertThat(value).isEqualTo(false);
value = gson.fromJson("true", boolean.class); value = gson.fromJson("true", boolean.class);
assertEquals(true, value); assertThat(value).isEqualTo(true);
} }
@Test @Test
public void testPrimitiveBooleanAutoboxedInASingleElementArraySerialization() { public void testPrimitiveBooleanAutoboxedInASingleElementArraySerialization() {
boolean target[] = {false}; boolean[] target = {false};
assertEquals("[false]", gson.toJson(target)); assertThat(gson.toJson(target)).isEqualTo("[false]");
assertEquals("[false]", gson.toJson(target, boolean[].class)); assertThat(gson.toJson(target, boolean[].class)).isEqualTo("[false]");
assertEquals("[false]", gson.toJson(target, Boolean[].class)); assertThat(gson.toJson(target, Boolean[].class)).isEqualTo("[false]");
} }
@Test @Test
public void testNumberSerialization() { public void testNumberSerialization() {
Number expected = 1L; Number expected = 1L;
String json = gson.toJson(expected); String json = gson.toJson(expected);
assertEquals(expected.toString(), json); assertThat(json).isEqualTo(expected.toString());
json = gson.toJson(expected, Number.class); json = gson.toJson(expected, Number.class);
assertEquals(expected.toString(), json); assertThat(json).isEqualTo(expected.toString());
} }
@Test @Test
@ -295,45 +292,45 @@ public class PrimitiveTest {
String json = "1"; String json = "1";
Number expected = Integer.valueOf(json); Number expected = Integer.valueOf(json);
Number actual = gson.fromJson(json, Number.class); Number actual = gson.fromJson(json, Number.class);
assertEquals(expected.intValue(), actual.intValue()); assertThat(actual.intValue()).isEqualTo(expected.intValue());
json = String.valueOf(Long.MAX_VALUE); json = String.valueOf(Long.MAX_VALUE);
expected = Long.valueOf(json); expected = Long.valueOf(json);
actual = gson.fromJson(json, Number.class); actual = gson.fromJson(json, Number.class);
assertEquals(expected.longValue(), actual.longValue()); assertThat(actual.longValue()).isEqualTo(expected.longValue());
json = "1.0"; json = "1.0";
actual = gson.fromJson(json, Number.class); actual = gson.fromJson(json, Number.class);
assertEquals(1L, actual.longValue()); assertThat(actual.longValue()).isEqualTo(1L);
} }
@Test @Test
public void testNumberAsStringDeserialization() { public void testNumberAsStringDeserialization() {
Number value = gson.fromJson("\"18\"", Number.class); Number value = gson.fromJson("\"18\"", Number.class);
assertEquals(18, value.intValue()); assertThat(value.intValue()).isEqualTo(18);
} }
@Test @Test
public void testPrimitiveDoubleAutoboxedSerialization() { public void testPrimitiveDoubleAutoboxedSerialization() {
assertEquals("-122.08234335", gson.toJson(-122.08234335D)); assertThat(gson.toJson(-122.08234335D)).isEqualTo("-122.08234335");
assertEquals("122.08112002", gson.toJson(122.08112002D)); assertThat(gson.toJson(122.08112002D)).isEqualTo("122.08112002");
} }
@Test @Test
public void testPrimitiveDoubleAutoboxedDeserialization() { public void testPrimitiveDoubleAutoboxedDeserialization() {
double actual = gson.fromJson("-122.08858585", double.class); double actual = gson.fromJson("-122.08858585", double.class);
assertEquals(-122.08858585D, actual, 0); assertThat(actual).isEqualTo(-122.08858585D);
actual = gson.fromJson("122.023900008000", Double.class); actual = gson.fromJson("122.023900008000", Double.class);
assertEquals(122.023900008D, actual, 0); assertThat(actual).isEqualTo(122.023900008D);
} }
@Test @Test
public void testPrimitiveDoubleAutoboxedInASingleElementArraySerialization() { public void testPrimitiveDoubleAutoboxedInASingleElementArraySerialization() {
double[] target = {-122.08D}; double[] target = {-122.08D};
assertEquals("[-122.08]", gson.toJson(target)); assertThat(gson.toJson(target)).isEqualTo("[-122.08]");
assertEquals("[-122.08]", gson.toJson(target, double[].class)); assertThat(gson.toJson(target, double[].class)).isEqualTo("[-122.08]");
assertEquals("[-122.08]", gson.toJson(target, Double[].class)); assertThat(gson.toJson(target, Double[].class)).isEqualTo("[-122.08]");
} }
@Test @Test
@ -341,10 +338,10 @@ public class PrimitiveTest {
String doubleValue = "1.0043E+5"; String doubleValue = "1.0043E+5";
Double expected = Double.valueOf(doubleValue); Double expected = Double.valueOf(doubleValue);
Double actual = gson.fromJson(doubleValue, Double.class); Double actual = gson.fromJson(doubleValue, Double.class);
assertEquals(expected, actual); assertThat(actual).isEqualTo(expected);
double actual1 = gson.fromJson(doubleValue, double.class); double actual1 = gson.fromJson(doubleValue, double.class);
assertEquals(expected, actual1, 0); assertThat(actual1).isEqualTo(expected);
} }
@Test @Test
@ -352,10 +349,10 @@ public class PrimitiveTest {
String doubleValue = "1E+5"; String doubleValue = "1E+5";
Double expected = Double.valueOf(doubleValue); Double expected = Double.valueOf(doubleValue);
Double actual = gson.fromJson(doubleValue, Double.class); Double actual = gson.fromJson(doubleValue, Double.class);
assertEquals(expected, actual); assertThat(actual).isEqualTo(expected);
double actual1 = gson.fromJson(doubleValue, double.class); double actual1 = gson.fromJson(doubleValue, double.class);
assertEquals(expected, actual1, 0); assertThat(actual1).isEqualTo(expected);
} }
@Test @Test
@ -363,13 +360,14 @@ public class PrimitiveTest {
String json = "[0.0, 0.004761904761904762, 3.4013606962703525E-4, 7.936508173034305E-4," String json = "[0.0, 0.004761904761904762, 3.4013606962703525E-4, 7.936508173034305E-4,"
+ "0.0011904761904761906, 0.0]"; + "0.0011904761904761906, 0.0]";
double[] values = gson.fromJson(json, double[].class); double[] values = gson.fromJson(json, double[].class);
assertEquals(6, values.length, 0);
assertEquals(0.0, values[0], 0); assertThat(values).hasLength(6);
assertEquals(0.004761904761904762, values[1], 0); assertThat(values[0]).isEqualTo(0.0);
assertEquals(3.4013606962703525E-4, values[2], 0); assertThat(values[1]).isEqualTo(0.004761904761904762);
assertEquals(7.936508173034305E-4, values[3], 0); assertThat(values[2]).isEqualTo(3.4013606962703525E-4);
assertEquals(0.0011904761904761906, values[4], 0); assertThat(values[3]).isEqualTo(7.936508173034305E-4);
assertEquals(0.0, values[5], 0); assertThat(values[4]).isEqualTo(0.0011904761904761906);
assertThat(values[5]).isEqualTo(0.0);
} }
@Test @Test
@ -377,24 +375,24 @@ public class PrimitiveTest {
String doubleValue = "1.234567899E8"; String doubleValue = "1.234567899E8";
Double expected = Double.valueOf(doubleValue); Double expected = Double.valueOf(doubleValue);
Double actual = gson.fromJson(doubleValue, Double.class); Double actual = gson.fromJson(doubleValue, Double.class);
assertEquals(expected, actual); assertThat(actual).isEqualTo(expected);
double actual1 = gson.fromJson(doubleValue, double.class); double actual1 = gson.fromJson(doubleValue, double.class);
assertEquals(expected, actual1, 0); assertThat(actual1).isEqualTo(expected);
} }
@Test @Test
public void testBigDecimalSerialization() { public void testBigDecimalSerialization() {
BigDecimal target = new BigDecimal("-122.0e-21"); BigDecimal target = new BigDecimal("-122.0e-21");
String json = gson.toJson(target); String json = gson.toJson(target);
assertEquals(target, new BigDecimal(json)); assertThat(new BigDecimal(json)).isEqualTo(target);
} }
@Test @Test
public void testBigDecimalDeserialization() { public void testBigDecimalDeserialization() {
BigDecimal target = new BigDecimal("-122.0e-21"); BigDecimal target = new BigDecimal("-122.0e-21");
String json = "-122.0e-21"; String json = "-122.0e-21";
assertEquals(target, gson.fromJson(json, BigDecimal.class)); assertThat(gson.fromJson(json, BigDecimal.class)).isEqualTo(target);
} }
@Test @Test
@ -402,25 +400,25 @@ public class PrimitiveTest {
BigDecimal[] target = {new BigDecimal("-122.08e-21")}; BigDecimal[] target = {new BigDecimal("-122.08e-21")};
String json = gson.toJson(target); String json = gson.toJson(target);
String actual = extractElementFromArray(json); String actual = extractElementFromArray(json);
assertEquals(target[0], new BigDecimal(actual)); assertThat(new BigDecimal(actual)).isEqualTo(target[0]);
json = gson.toJson(target, BigDecimal[].class); json = gson.toJson(target, BigDecimal[].class);
actual = extractElementFromArray(json); actual = extractElementFromArray(json);
assertEquals(target[0], new BigDecimal(actual)); assertThat(new BigDecimal(actual)).isEqualTo(target[0]);
} }
@Test @Test
public void testSmallValueForBigDecimalSerialization() { public void testSmallValueForBigDecimalSerialization() {
BigDecimal target = new BigDecimal("1.55"); BigDecimal target = new BigDecimal("1.55");
String actual = gson.toJson(target); String actual = gson.toJson(target);
assertEquals(target.toString(), actual); assertThat(actual).isEqualTo(target.toString());
} }
@Test @Test
public void testSmallValueForBigDecimalDeserialization() { public void testSmallValueForBigDecimalDeserialization() {
BigDecimal expected = new BigDecimal("1.55"); BigDecimal expected = new BigDecimal("1.55");
BigDecimal actual = gson.fromJson("1.55", BigDecimal.class); BigDecimal actual = gson.fromJson("1.55", BigDecimal.class);
assertEquals(expected, actual); assertThat(actual).isEqualTo(expected);
} }
@Test @Test
@ -429,7 +427,7 @@ public class PrimitiveTest {
BigDecimal obj = new BigDecimal(expectedValue); BigDecimal obj = new BigDecimal(expectedValue);
String actualValue = gson.toJson(obj); String actualValue = gson.toJson(obj);
assertEquals(expectedValue, actualValue); assertThat(actualValue).isEqualTo(expectedValue);
} }
@Test @Test
@ -438,7 +436,7 @@ public class PrimitiveTest {
BigDecimal expected = new BigDecimal(json); BigDecimal expected = new BigDecimal(json);
BigDecimal actual = gson.fromJson(json, BigDecimal.class); BigDecimal actual = gson.fromJson(json, BigDecimal.class);
assertEquals(expected, actual); assertThat(actual).isEqualTo(expected);
} }
@Test @Test
@ -446,7 +444,7 @@ public class PrimitiveTest {
String doubleValue = "0.05E+5"; String doubleValue = "0.05E+5";
BigDecimal expected = new BigDecimal(doubleValue); BigDecimal expected = new BigDecimal(doubleValue);
BigDecimal actual = gson.fromJson(doubleValue, BigDecimal.class); BigDecimal actual = gson.fromJson(doubleValue, BigDecimal.class);
assertEquals(expected, actual); assertThat(actual).isEqualTo(expected);
} }
@Test @Test
@ -454,20 +452,20 @@ public class PrimitiveTest {
String doubleValue = "5E+5"; String doubleValue = "5E+5";
BigDecimal expected = new BigDecimal(doubleValue); BigDecimal expected = new BigDecimal(doubleValue);
BigDecimal actual = gson.fromJson(doubleValue, BigDecimal.class); BigDecimal actual = gson.fromJson(doubleValue, BigDecimal.class);
assertEquals(expected, actual); assertThat(actual).isEqualTo(expected);
} }
@Test @Test
public void testBigIntegerSerialization() { public void testBigIntegerSerialization() {
BigInteger target = new BigInteger("12121211243123245845384534687435634558945453489543985435"); BigInteger target = new BigInteger("12121211243123245845384534687435634558945453489543985435");
assertEquals(target.toString(), gson.toJson(target)); assertThat(gson.toJson(target)).isEqualTo(target.toString());
} }
@Test @Test
public void testBigIntegerDeserialization() { public void testBigIntegerDeserialization() {
String json = "12121211243123245845384534687435634558945453489543985435"; String json = "12121211243123245845384534687435634558945453489543985435";
BigInteger target = new BigInteger(json); BigInteger target = new BigInteger(json);
assertEquals(target, gson.fromJson(json, BigInteger.class)); assertThat(gson.fromJson(json, BigInteger.class)).isEqualTo(target);
} }
@Test @Test
@ -475,25 +473,25 @@ public class PrimitiveTest {
BigInteger[] target = {new BigInteger("1212121243434324323254365345367456456456465464564564")}; BigInteger[] target = {new BigInteger("1212121243434324323254365345367456456456465464564564")};
String json = gson.toJson(target); String json = gson.toJson(target);
String actual = extractElementFromArray(json); String actual = extractElementFromArray(json);
assertEquals(target[0], new BigInteger(actual)); assertThat(new BigInteger(actual)).isEqualTo(target[0]);
json = gson.toJson(target, BigInteger[].class); json = gson.toJson(target, BigInteger[].class);
actual = extractElementFromArray(json); actual = extractElementFromArray(json);
assertEquals(target[0], new BigInteger(actual)); assertThat(new BigInteger(actual)).isEqualTo(target[0]);
} }
@Test @Test
public void testSmallValueForBigIntegerSerialization() { public void testSmallValueForBigIntegerSerialization() {
BigInteger target = new BigInteger("15"); BigInteger target = new BigInteger("15");
String actual = gson.toJson(target); String actual = gson.toJson(target);
assertEquals(target.toString(), actual); assertThat(actual).isEqualTo(target.toString());
} }
@Test @Test
public void testSmallValueForBigIntegerDeserialization() { public void testSmallValueForBigIntegerDeserialization() {
BigInteger expected = new BigInteger("15"); BigInteger expected = new BigInteger("15");
BigInteger actual = gson.fromJson("15", BigInteger.class); BigInteger actual = gson.fromJson("15", BigInteger.class);
assertEquals(expected, actual); assertThat(actual).isEqualTo(expected);
} }
@Test @Test
@ -508,14 +506,14 @@ public class PrimitiveTest {
public void testLazilyParsedNumberSerialization() { public void testLazilyParsedNumberSerialization() {
LazilyParsedNumber target = new LazilyParsedNumber("1.5"); LazilyParsedNumber target = new LazilyParsedNumber("1.5");
String actual = gson.toJson(target); String actual = gson.toJson(target);
assertEquals("1.5", actual); assertThat(actual).isEqualTo("1.5");
} }
@Test @Test
public void testLazilyParsedNumberDeserialization() { public void testLazilyParsedNumberDeserialization() {
LazilyParsedNumber expected = new LazilyParsedNumber("1.5"); LazilyParsedNumber expected = new LazilyParsedNumber("1.5");
LazilyParsedNumber actual = gson.fromJson("1.5", LazilyParsedNumber.class); LazilyParsedNumber actual = gson.fromJson("1.5", LazilyParsedNumber.class);
assertEquals(expected, actual); assertThat(actual).isEqualTo(expected);
} }
@Test @Test
@ -526,7 +524,7 @@ public class PrimitiveTest {
Serializable serializableString = expected; Serializable serializableString = expected;
String actualJson = gson.toJson(serializableString, Serializable.class); String actualJson = gson.toJson(serializableString, Serializable.class);
assertFalse(expectedJson.equals(actualJson)); assertThat(actualJson).isNotEqualTo(expectedJson);
} }
private String extractElementFromArray(String json) { private String extractElementFromArray(String json) {
@ -552,14 +550,14 @@ public class PrimitiveTest {
public void testDoubleNaNSerialization() { public void testDoubleNaNSerialization() {
Gson gson = new GsonBuilder().serializeSpecialFloatingPointValues().create(); Gson gson = new GsonBuilder().serializeSpecialFloatingPointValues().create();
double nan = Double.NaN; double nan = Double.NaN;
assertEquals("NaN", gson.toJson(nan)); assertThat(gson.toJson(nan)).isEqualTo("NaN");
assertEquals("NaN", gson.toJson(Double.NaN)); assertThat(gson.toJson(Double.NaN)).isEqualTo("NaN");
} }
@Test @Test
public void testDoubleNaNDeserialization() { public void testDoubleNaNDeserialization() {
assertTrue(Double.isNaN(gson.fromJson("NaN", Double.class))); assertThat(Double.isNaN(gson.fromJson("NaN", Double.class))).isTrue();
assertTrue(Double.isNaN(gson.fromJson("NaN", double.class))); assertThat(Double.isNaN(gson.fromJson("NaN", double.class))).isTrue();
} }
@Test @Test
@ -581,14 +579,14 @@ public class PrimitiveTest {
public void testFloatNaNSerialization() { public void testFloatNaNSerialization() {
Gson gson = new GsonBuilder().serializeSpecialFloatingPointValues().create(); Gson gson = new GsonBuilder().serializeSpecialFloatingPointValues().create();
float nan = Float.NaN; float nan = Float.NaN;
assertEquals("NaN", gson.toJson(nan)); assertThat(gson.toJson(nan)).isEqualTo("NaN");
assertEquals("NaN", gson.toJson(Float.NaN)); assertThat(gson.toJson(Float.NaN)).isEqualTo("NaN");
} }
@Test @Test
public void testFloatNaNDeserialization() { public void testFloatNaNDeserialization() {
assertTrue(Float.isNaN(gson.fromJson("NaN", Float.class))); assertThat(Float.isNaN(gson.fromJson("NaN", Float.class))).isTrue();
assertTrue(Float.isNaN(gson.fromJson("NaN", float.class))); assertThat(Float.isNaN(gson.fromJson("NaN", float.class))).isTrue();
} }
@Test @Test
@ -619,14 +617,14 @@ public class PrimitiveTest {
public void testDoubleInfinitySerialization() { public void testDoubleInfinitySerialization() {
Gson gson = new GsonBuilder().serializeSpecialFloatingPointValues().create(); Gson gson = new GsonBuilder().serializeSpecialFloatingPointValues().create();
double infinity = Double.POSITIVE_INFINITY; double infinity = Double.POSITIVE_INFINITY;
assertEquals("Infinity", gson.toJson(infinity)); assertThat(gson.toJson(infinity)).isEqualTo("Infinity");
assertEquals("Infinity", gson.toJson(Double.POSITIVE_INFINITY)); assertThat(gson.toJson(Double.POSITIVE_INFINITY)).isEqualTo("Infinity");
} }
@Test @Test
public void testDoubleInfinityDeserialization() { public void testDoubleInfinityDeserialization() {
assertTrue(Double.isInfinite(gson.fromJson("Infinity", Double.class))); assertThat(Double.isInfinite(gson.fromJson("Infinity", Double.class))).isTrue();
assertTrue(Double.isInfinite(gson.fromJson("Infinity", double.class))); assertThat(Double.isInfinite(gson.fromJson("Infinity", double.class))).isTrue();
} }
@Test @Test
@ -648,14 +646,14 @@ public class PrimitiveTest {
public void testFloatInfinitySerialization() { public void testFloatInfinitySerialization() {
Gson gson = new GsonBuilder().serializeSpecialFloatingPointValues().create(); Gson gson = new GsonBuilder().serializeSpecialFloatingPointValues().create();
float infinity = Float.POSITIVE_INFINITY; float infinity = Float.POSITIVE_INFINITY;
assertEquals("Infinity", gson.toJson(infinity)); assertThat(gson.toJson(infinity)).isEqualTo("Infinity");
assertEquals("Infinity", gson.toJson(Float.POSITIVE_INFINITY)); assertThat(gson.toJson(Float.POSITIVE_INFINITY)).isEqualTo("Infinity");
} }
@Test @Test
public void testFloatInfinityDeserialization() { public void testFloatInfinityDeserialization() {
assertTrue(Float.isInfinite(gson.fromJson("Infinity", Float.class))); assertThat(Float.isInfinite(gson.fromJson("Infinity", Float.class))).isTrue();
assertTrue(Float.isInfinite(gson.fromJson("Infinity", float.class))); assertThat(Float.isInfinite(gson.fromJson("Infinity", float.class))).isTrue();
} }
@Test @Test
@ -686,14 +684,14 @@ public class PrimitiveTest {
public void testNegativeInfinitySerialization() { public void testNegativeInfinitySerialization() {
Gson gson = new GsonBuilder().serializeSpecialFloatingPointValues().create(); Gson gson = new GsonBuilder().serializeSpecialFloatingPointValues().create();
double negativeInfinity = Double.NEGATIVE_INFINITY; double negativeInfinity = Double.NEGATIVE_INFINITY;
assertEquals("-Infinity", gson.toJson(negativeInfinity)); assertThat(gson.toJson(negativeInfinity)).isEqualTo("-Infinity");
assertEquals("-Infinity", gson.toJson(Double.NEGATIVE_INFINITY)); assertThat(gson.toJson(Double.NEGATIVE_INFINITY)).isEqualTo("-Infinity");
} }
@Test @Test
public void testNegativeInfinityDeserialization() { public void testNegativeInfinityDeserialization() {
assertTrue(Double.isInfinite(gson.fromJson("-Infinity", double.class))); assertThat(Double.isInfinite(gson.fromJson("-Infinity", double.class))).isTrue();
assertTrue(Double.isInfinite(gson.fromJson("-Infinity", Double.class))); assertThat(Double.isInfinite(gson.fromJson("-Infinity", Double.class))).isTrue();
} }
@Test @Test
@ -715,14 +713,14 @@ public class PrimitiveTest {
public void testNegativeInfinityFloatSerialization() { public void testNegativeInfinityFloatSerialization() {
Gson gson = new GsonBuilder().serializeSpecialFloatingPointValues().create(); Gson gson = new GsonBuilder().serializeSpecialFloatingPointValues().create();
float negativeInfinity = Float.NEGATIVE_INFINITY; float negativeInfinity = Float.NEGATIVE_INFINITY;
assertEquals("-Infinity", gson.toJson(negativeInfinity)); assertThat(gson.toJson(negativeInfinity)).isEqualTo("-Infinity");
assertEquals("-Infinity", gson.toJson(Float.NEGATIVE_INFINITY)); assertThat(gson.toJson(Float.NEGATIVE_INFINITY)).isEqualTo("-Infinity");
} }
@Test @Test
public void testNegativeInfinityFloatDeserialization() { public void testNegativeInfinityFloatDeserialization() {
assertTrue(Float.isInfinite(gson.fromJson("-Infinity", float.class))); assertThat(Float.isInfinite(gson.fromJson("-Infinity", float.class))).isTrue();
assertTrue(Float.isInfinite(gson.fromJson("-Infinity", Float.class))); assertThat(Float.isInfinite(gson.fromJson("-Infinity", Float.class))).isTrue();
} }
@Test @Test
@ -735,39 +733,39 @@ public class PrimitiveTest {
} }
@Test @Test
public void testLongAsStringSerialization() throws Exception { public void testLongAsStringSerialization() {
gson = new GsonBuilder().setLongSerializationPolicy(LongSerializationPolicy.STRING).create(); gson = new GsonBuilder().setLongSerializationPolicy(LongSerializationPolicy.STRING).create();
String result = gson.toJson(15L); String result = gson.toJson(15L);
assertEquals("\"15\"", result); assertThat(result).isEqualTo("\"15\"");
// Test with an integer and ensure its still a number // Test with an integer and ensure its still a number
result = gson.toJson(2); result = gson.toJson(2);
assertEquals("2", result); assertThat(result).isEqualTo("2");
} }
@Test @Test
public void testLongAsStringDeserialization() throws Exception { public void testLongAsStringDeserialization() {
long value = gson.fromJson("\"15\"", long.class); long value = gson.fromJson("\"15\"", long.class);
assertEquals(15, value); assertThat(value).isEqualTo(15);
gson = new GsonBuilder().setLongSerializationPolicy(LongSerializationPolicy.STRING).create(); gson = new GsonBuilder().setLongSerializationPolicy(LongSerializationPolicy.STRING).create();
value = gson.fromJson("\"25\"", long.class); value = gson.fromJson("\"25\"", long.class);
assertEquals(25, value); assertThat(value).isEqualTo(25);
} }
@Test @Test
public void testQuotedStringSerializationAndDeserialization() throws Exception { public void testQuotedStringSerializationAndDeserialization() {
String value = "String Blah Blah Blah...1, 2, 3"; String value = "String Blah Blah Blah...1, 2, 3";
String serializedForm = gson.toJson(value); String serializedForm = gson.toJson(value);
assertEquals("\"" + value + "\"", serializedForm); assertThat(serializedForm).isEqualTo("\"" + value + "\"");
String actual = gson.fromJson(serializedForm, String.class); String actual = gson.fromJson(serializedForm, String.class);
assertEquals(value, actual); assertThat(actual).isEqualTo(value);
} }
@Test @Test
public void testUnquotedStringDeserializationFails() throws Exception { public void testUnquotedStringDeserializationFails() {
assertEquals("UnquotedSingleWord", gson.fromJson("UnquotedSingleWord", String.class)); assertThat(gson.fromJson("UnquotedSingleWord", String.class)).isEqualTo("UnquotedSingleWord");
String value = "String Blah Blah Blah...1, 2, 3"; String value = "String Blah Blah Blah...1, 2, 3";
try { try {
@ -777,21 +775,21 @@ public class PrimitiveTest {
} }
@Test @Test
public void testHtmlCharacterSerialization() throws Exception { public void testHtmlCharacterSerialization() {
String target = "<script>var a = 12;</script>"; String target = "<script>var a = 12;</script>";
String result = gson.toJson(target); String result = gson.toJson(target);
assertFalse(result.equals('"' + target + '"')); assertThat(result).isNotEqualTo('"' + target + '"');
gson = new GsonBuilder().disableHtmlEscaping().create(); gson = new GsonBuilder().disableHtmlEscaping().create();
result = gson.toJson(target); result = gson.toJson(target);
assertTrue(result.equals('"' + target + '"')); assertThat(result).isEqualTo('"' + target + '"');
} }
@Test @Test
public void testDeserializePrimitiveWrapperAsObjectField() { public void testDeserializePrimitiveWrapperAsObjectField() {
String json = "{i:10}"; String json = "{i:10}";
ClassWithIntegerField target = gson.fromJson(json, ClassWithIntegerField.class); ClassWithIntegerField target = gson.fromJson(json, ClassWithIntegerField.class);
assertEquals(10, target.i.intValue()); assertThat(target.i).isEqualTo(10);
} }
private static class ClassWithIntegerField { private static class ClassWithIntegerField {
@ -800,9 +798,9 @@ public class PrimitiveTest {
@Test @Test
public void testPrimitiveClassLiteral() { public void testPrimitiveClassLiteral() {
assertEquals(1, gson.fromJson("1", int.class).intValue()); assertThat(gson.fromJson("1", int.class)).isEqualTo(1);
assertEquals(1, gson.fromJson(new StringReader("1"), int.class).intValue()); assertThat(gson.fromJson(new StringReader("1"), int.class)).isEqualTo(1);
assertEquals(1, gson.fromJson(new JsonPrimitive(1), int.class).intValue()); assertThat(gson.fromJson(new JsonPrimitive(1), int.class)).isEqualTo(1);
} }
@Test @Test
@ -967,7 +965,7 @@ public class PrimitiveTest {
@Test @Test
public void testDeserializingDecimalPointValueZeroSucceeds() { public void testDeserializingDecimalPointValueZeroSucceeds() {
assertEquals(1, (int) gson.fromJson("1.0", Integer.class)); assertThat(gson.fromJson("1.0", Integer.class)).isEqualTo(1);
} }
@Test @Test
@ -1023,28 +1021,28 @@ public class PrimitiveTest {
@Test @Test
public void testValueVeryCloseToZeroIsZero() { public void testValueVeryCloseToZeroIsZero() {
assertEquals(0, (byte) gson.fromJson("-122.08e-2132", byte.class)); assertThat(gson.fromJson("-122.08e-2132", byte.class)).isEqualTo(0);
assertEquals(0, (short) gson.fromJson("-122.08e-2132", short.class)); assertThat(gson.fromJson("-122.08e-2132", short.class)).isEqualTo(0);
assertEquals(0, (int) gson.fromJson("-122.08e-2132", int.class)); assertThat(gson.fromJson("-122.08e-2132", int.class)).isEqualTo(0);
assertEquals(0, (long) gson.fromJson("-122.08e-2132", long.class)); assertThat(gson.fromJson("-122.08e-2132", long.class)).isEqualTo(0);
assertEquals(-0.0f, gson.fromJson("-122.08e-2132", float.class), 0); assertThat(gson.fromJson("-122.08e-2132", float.class)).isEqualTo(-0.0f);
assertEquals(-0.0, gson.fromJson("-122.08e-2132", double.class), 0); assertThat(gson.fromJson("-122.08e-2132", double.class)).isEqualTo(-0.0);
assertEquals(0.0f, gson.fromJson("122.08e-2132", float.class), 0); assertThat(gson.fromJson("122.08e-2132", float.class)).isEqualTo(0.0f);
assertEquals(0.0, gson.fromJson("122.08e-2132", double.class), 0); assertThat(gson.fromJson("122.08e-2132", double.class)).isEqualTo(0.0);
} }
@Test @Test
public void testDeserializingBigDecimalAsFloat() { public void testDeserializingBigDecimalAsFloat() {
String json = "-122.08e-2132332"; String json = "-122.08e-2132332";
float actual = gson.fromJson(json, float.class); float actual = gson.fromJson(json, float.class);
assertEquals(-0.0f, actual, 0); assertThat(actual).isEqualTo(-0.0f);
} }
@Test @Test
public void testDeserializingBigDecimalAsDouble() { public void testDeserializingBigDecimalAsDouble() {
String json = "-122.08e-2132332"; String json = "-122.08e-2132332";
double actual = gson.fromJson(json, double.class); double actual = gson.fromJson(json, double.class);
assertEquals(-0.0d, actual, 0); assertThat(actual).isEqualTo(-0.0d);
} }
@Test @Test
@ -1060,13 +1058,12 @@ public class PrimitiveTest {
public void testDeserializingBigIntegerAsBigDecimal() { public void testDeserializingBigIntegerAsBigDecimal() {
BigDecimal actual = BigDecimal actual =
gson.fromJson("12121211243123245845384534687435634558945453489543985435", BigDecimal.class); gson.fromJson("12121211243123245845384534687435634558945453489543985435", BigDecimal.class);
assertEquals("12121211243123245845384534687435634558945453489543985435", actual.toPlainString()); assertThat(actual.toPlainString()).isEqualTo("12121211243123245845384534687435634558945453489543985435");
} }
@Test @Test
public void testStringsAsBooleans() { public void testStringsAsBooleans() {
String json = "['true', 'false', 'TRUE', 'yes', '1']"; String json = "['true', 'false', 'TRUE', 'yes', '1']";
assertEquals(Arrays.asList(true, false, true, false, false), assertThat( gson.<List<Boolean>>fromJson(json, new TypeToken<List<Boolean>>() {}.getType())).isEqualTo(Arrays.asList(true, false, true, false, false));
gson.<List<Boolean>>fromJson(json, new TypeToken<List<Boolean>>() {}.getType()));
} }
} }

View File

@ -16,8 +16,7 @@
package com.google.gson.functional; package com.google.gson.functional;
import static org.junit.Assert.assertFalse; import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertTrue;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;
@ -64,8 +63,8 @@ public class PrintFormattingTest {
obj.addProperty("field1", "value1"); obj.addProperty("field1", "value1");
obj.addProperty("field2", (String) null); obj.addProperty("field2", (String) null);
String json = gson.toJson(obj); String json = gson.toJson(obj);
assertTrue(json.contains("field1")); assertThat(json).contains("field1");
assertFalse(json.contains("field2")); assertThat(json).doesNotContain("field2");
} }
@Test @Test
@ -75,13 +74,13 @@ public class PrintFormattingTest {
obj.addProperty("field1", "value1"); obj.addProperty("field1", "value1");
obj.addProperty("field2", (String) null); obj.addProperty("field2", (String) null);
String json = gson.toJson(obj); String json = gson.toJson(obj);
assertTrue(json.contains("field1")); assertThat(json).contains("field1");
assertTrue(json.contains("field2")); assertThat(json).contains("field2");
} }
private static void assertContainsNoWhiteSpace(String str) { private static void assertContainsNoWhiteSpace(String str) {
for (char c : str.toCharArray()) { for (char c : str.toCharArray()) {
assertFalse(Character.isWhitespace(c)); assertThat(Character.isWhitespace(c)).isFalse();
} }
} }
} }

View File

@ -15,7 +15,7 @@
*/ */
package com.google.gson.functional; 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.Gson;
import com.google.gson.reflect.TypeToken; import com.google.gson.reflect.TypeToken;
@ -42,14 +42,14 @@ public class RawSerializationTest {
public void testCollectionOfPrimitives() { public void testCollectionOfPrimitives() {
Collection<Integer> ints = Arrays.asList(1, 2, 3, 4, 5); Collection<Integer> ints = Arrays.asList(1, 2, 3, 4, 5);
String json = gson.toJson(ints); String json = gson.toJson(ints);
assertEquals("[1,2,3,4,5]", json); assertThat(json).isEqualTo("[1,2,3,4,5]");
} }
@Test @Test
public void testCollectionOfObjects() { public void testCollectionOfObjects() {
Collection<Foo> foos = Arrays.asList(new Foo(1), new Foo(2)); Collection<Foo> foos = Arrays.asList(new Foo(1), new Foo(2));
String json = gson.toJson(foos); String json = gson.toJson(foos);
assertEquals("[{\"b\":1},{\"b\":2}]", json); assertThat(json).isEqualTo("[{\"b\":1},{\"b\":2}]");
} }
@Test @Test
@ -58,10 +58,10 @@ public class RawSerializationTest {
String expectedJson = "{\"t\":{\"b\":1}}"; String expectedJson = "{\"t\":{\"b\":1}}";
// Ensure that serialization works without specifying the type explicitly // Ensure that serialization works without specifying the type explicitly
String json = gson.toJson(bar); String json = gson.toJson(bar);
assertEquals(expectedJson, json); assertThat(json).isEqualTo(expectedJson);
// Ensure that serialization also works when the type is specified explicitly // Ensure that serialization also works when the type is specified explicitly
json = gson.toJson(bar, new TypeToken<Bar<Foo>>(){}.getType()); json = gson.toJson(bar, new TypeToken<Bar<Foo>>(){}.getType());
assertEquals(expectedJson, json); assertThat(json).isEqualTo(expectedJson);
} }
@Test @Test
@ -70,10 +70,10 @@ public class RawSerializationTest {
String expectedJson = "{\"t\":{\"t\":{\"b\":1}}}"; String expectedJson = "{\"t\":{\"t\":{\"b\":1}}}";
// Ensure that serialization works without specifying the type explicitly // Ensure that serialization works without specifying the type explicitly
String json = gson.toJson(bar); String json = gson.toJson(bar);
assertEquals(expectedJson, json); assertThat(json).isEqualTo(expectedJson);
// Ensure that serialization also works when the type is specified explicitly // Ensure that serialization also works when the type is specified explicitly
json = gson.toJson(bar, new TypeToken<Bar<Bar<Foo>>>(){}.getType()); json = gson.toJson(bar, new TypeToken<Bar<Bar<Foo>>>(){}.getType());
assertEquals(expectedJson, json); assertThat(json).isEqualTo(expectedJson);
} }
@Test @Test
@ -82,10 +82,10 @@ public class RawSerializationTest {
String expectedJson = "{\"t\":{\"t\":{\"t\":{\"b\":1}}}}"; String expectedJson = "{\"t\":{\"t\":{\"t\":{\"b\":1}}}}";
// Ensure that serialization works without specifying the type explicitly // Ensure that serialization works without specifying the type explicitly
String json = gson.toJson(bar); String json = gson.toJson(bar);
assertEquals(expectedJson, json); assertThat(json).isEqualTo(expectedJson);
// Ensure that serialization also works when the type is specified explicitly // Ensure that serialization also works when the type is specified explicitly
json = gson.toJson(bar, new TypeToken<Bar<Bar<Bar<Foo>>>>(){}.getType()); json = gson.toJson(bar, new TypeToken<Bar<Bar<Bar<Foo>>>>(){}.getType());
assertEquals(expectedJson, json); assertThat(json).isEqualTo(expectedJson);
} }
private static class Foo { private static class Foo {

View File

@ -15,10 +15,7 @@
*/ */
package com.google.gson.functional; package com.google.gson.functional;
import static org.junit.Assert.assertEquals; import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import com.google.gson.Gson; import com.google.gson.Gson;
@ -54,33 +51,33 @@ public class ReadersWritersTest {
} }
@Test @Test
public void testWriterForSerialization() throws Exception { public void testWriterForSerialization() {
Writer writer = new StringWriter(); Writer writer = new StringWriter();
BagOfPrimitives src = new BagOfPrimitives(); BagOfPrimitives src = new BagOfPrimitives();
gson.toJson(src, writer); gson.toJson(src, writer);
assertEquals(src.getExpectedJson(), writer.toString()); assertThat(writer.toString()).isEqualTo(src.getExpectedJson());
} }
@Test @Test
public void testReaderForDeserialization() throws Exception { public void testReaderForDeserialization() {
BagOfPrimitives expected = new BagOfPrimitives(); BagOfPrimitives expected = new BagOfPrimitives();
Reader json = new StringReader(expected.getExpectedJson()); Reader json = new StringReader(expected.getExpectedJson());
BagOfPrimitives actual = gson.fromJson(json, BagOfPrimitives.class); BagOfPrimitives actual = gson.fromJson(json, BagOfPrimitives.class);
assertEquals(expected, actual); assertThat(actual).isEqualTo(expected);
} }
@Test @Test
public void testTopLevelNullObjectSerializationWithWriter() { public void testTopLevelNullObjectSerializationWithWriter() {
StringWriter writer = new StringWriter(); StringWriter writer = new StringWriter();
gson.toJson(null, writer); gson.toJson(null, writer);
assertEquals("null", writer.toString()); assertThat(writer.toString()).isEqualTo("null");
} }
@Test @Test
public void testTopLevelNullObjectDeserializationWithReader() { public void testTopLevelNullObjectDeserializationWithReader() {
StringReader reader = new StringReader("null"); StringReader reader = new StringReader("null");
Integer nullIntObject = gson.fromJson(reader, Integer.class); Integer nullIntObject = gson.fromJson(reader, Integer.class);
assertNull(nullIntObject); assertThat(nullIntObject).isNull();
} }
@Test @Test
@ -88,7 +85,7 @@ public class ReadersWritersTest {
Gson gson = new GsonBuilder().serializeNulls().create(); Gson gson = new GsonBuilder().serializeNulls().create();
StringWriter writer = new StringWriter(); StringWriter writer = new StringWriter();
gson.toJson(null, writer); gson.toJson(null, writer);
assertEquals("null", writer.toString()); assertThat(writer.toString()).isEqualTo("null");
} }
@Test @Test
@ -96,7 +93,7 @@ public class ReadersWritersTest {
Gson gson = new GsonBuilder().serializeNulls().create(); Gson gson = new GsonBuilder().serializeNulls().create();
StringReader reader = new StringReader("null"); StringReader reader = new StringReader("null");
Integer nullIntObject = gson.fromJson(reader, Integer.class); Integer nullIntObject = gson.fromJson(reader, Integer.class);
assertNull(nullIntObject); assertThat(nullIntObject).isNull();
} }
@Test @Test
@ -108,9 +105,9 @@ public class ReadersWritersTest {
CharArrayReader reader = new CharArrayReader(writer.toCharArray()); CharArrayReader reader = new CharArrayReader(writer.toCharArray());
JsonStreamParser parser = new JsonStreamParser(reader); JsonStreamParser parser = new JsonStreamParser(reader);
String actualOne = gson.fromJson(parser.next(), String.class); String actualOne = gson.fromJson(parser.next(), String.class);
assertEquals("one", actualOne); assertThat(actualOne).isEqualTo("one");
String actualTwo = gson.fromJson(parser.next(), String.class); String actualTwo = gson.fromJson(parser.next(), String.class);
assertEquals("two", actualTwo); assertThat(actualTwo).isEqualTo("two");
} }
@Test @Test
@ -124,10 +121,10 @@ public class ReadersWritersTest {
CharArrayReader reader = new CharArrayReader(writer.toCharArray()); CharArrayReader reader = new CharArrayReader(writer.toCharArray());
JsonStreamParser parser = new JsonStreamParser(reader); JsonStreamParser parser = new JsonStreamParser(reader);
BagOfPrimitives actualOne = gson.fromJson(parser.next(), BagOfPrimitives.class); 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); BagOfPrimitives actualTwo = gson.fromJson(parser.next(), BagOfPrimitives.class);
assertEquals("two", actualTwo.stringValue); assertThat(actualTwo.stringValue).isEqualTo("two");
assertFalse(parser.hasNext()); assertThat(parser.hasNext()).isFalse();
} }
@Test @Test
@ -191,7 +188,7 @@ public class ReadersWritersTest {
gson.toJson(Arrays.asList("test", 123, true), appendable); gson.toJson(Arrays.asList("test", 123, true), appendable);
// Make sure CharSequence.toString() was called at least two times to verify that // Make sure CharSequence.toString() was called at least two times to verify that
// CurrentWrite.cachedString is properly overwritten when char array changes // CurrentWrite.cachedString is properly overwritten when char array changes
assertTrue(appendable.toStringCallCount >= 2); assertThat(appendable.toStringCallCount >= 2).isTrue();
assertEquals("[\"test\",123,true]", appendable.stringBuilder.toString()); assertThat(appendable.stringBuilder.toString()).isEqualTo("[\"test\",123,true]");
} }
} }

View File

@ -1,8 +1,8 @@
package com.google.gson.functional; 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.Assert.fail;
import static org.junit.Assume.assumeNotNull; import static org.junit.Assume.assumeNotNull;;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;
@ -52,12 +52,10 @@ public class ReflectionAccessFilterTest {
fail("Expected exception; test needs to be run with Java >= 9"); fail("Expected exception; test needs to be run with Java >= 9");
} catch (JsonIOException expected) { } catch (JsonIOException expected) {
// Note: This test is rather brittle and depends on the JDK implementation // Note: This test is rather brittle and depends on the JDK implementation
assertEquals( assertThat(expected).hasMessageThat()
"Field 'java.io.File#path' is not accessible and ReflectionAccessFilter does not permit" .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" + " 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.", + " filter or increase the visibility of the element and its declaring type.");
expected.getMessage()
);
} }
@ -72,7 +70,7 @@ public class ReflectionAccessFilterTest {
Constructor<?> pointConstructor = pointClass.getConstructor(int.class, int.class); Constructor<?> pointConstructor = pointClass.getConstructor(int.class, int.class);
Object point = pointConstructor.newInstance(1, 2); Object point = pointConstructor.newInstance(1, 2);
String json = gson.toJson(point); String json = gson.toJson(point);
assertEquals("{\"x\":1,\"y\":2}", json); assertThat(json).isEqualTo("{\"x\":1,\"y\":2}");
} }
@Test @Test
@ -85,12 +83,10 @@ public class ReflectionAccessFilterTest {
gson.toJson(new ClassExtendingJdkClass()); gson.toJson(new ClassExtendingJdkClass());
fail("Expected exception; test needs to be run with Java >= 9"); fail("Expected exception; test needs to be run with Java >= 9");
} catch (JsonIOException expected) { } catch (JsonIOException expected) {
assertEquals( assertThat(expected).hasMessageThat()
"Field 'java.io.Reader#lock' is not accessible and ReflectionAccessFilter does not permit" .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" + " 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.", + " filter or increase the visibility of the element and its declaring type.");
expected.getMessage()
);
} }
} }
@ -105,11 +101,9 @@ public class ReflectionAccessFilterTest {
gson.toJson(Thread.currentThread()); gson.toJson(Thread.currentThread());
fail(); fail();
} catch (JsonIOException expected) { } catch (JsonIOException expected) {
assertEquals( assertThat(expected).hasMessageThat()
"ReflectionAccessFilter does not permit using reflection for class java.lang.Thread." .isEqualTo("ReflectionAccessFilter does not permit using reflection for class java.lang.Thread."
+ " Register a TypeAdapter for this type or adjust the access filter.", + " Register a TypeAdapter for this type or adjust the access filter.");
expected.getMessage()
);
} }
} }
@ -123,12 +117,10 @@ public class ReflectionAccessFilterTest {
gson.toJson(new ClassExtendingJdkClass()); gson.toJson(new ClassExtendingJdkClass());
fail(); fail();
} catch (JsonIOException expected) { } catch (JsonIOException expected) {
assertEquals( assertThat(expected).hasMessageThat()
"ReflectionAccessFilter does not permit using reflection for class java.io.Reader" .isEqualTo("ReflectionAccessFilter does not permit using reflection for class java.io.Reader"
+ " (supertype of class com.google.gson.functional.ReflectionAccessFilterTest$ClassExtendingJdkClass)." + " (supertype of class com.google.gson.functional.ReflectionAccessFilterTest$ClassExtendingJdkClass)."
+ " Register a TypeAdapter for this type or adjust the access filter.", + " Register a TypeAdapter for this type or adjust the access filter.");
expected.getMessage()
);
} }
} }
@ -153,13 +145,11 @@ public class ReflectionAccessFilterTest {
gson.toJson(new ClassWithStaticField()); gson.toJson(new ClassWithStaticField());
fail("Expected exception; test needs to be run with Java >= 9"); fail("Expected exception; test needs to be run with Java >= 9");
} catch (JsonIOException expected) { } catch (JsonIOException expected) {
assertEquals( assertThat(expected).hasMessageThat()
"Field 'com.google.gson.functional.ReflectionAccessFilterTest$ClassWithStaticField#i'" .isEqualTo("Field 'com.google.gson.functional.ReflectionAccessFilterTest$ClassWithStaticField#i'"
+ " is not accessible and ReflectionAccessFilter does not permit making it accessible." + " is not accessible and ReflectionAccessFilter does not permit making it accessible."
+ " Register a TypeAdapter for the declaring type, adjust the access filter or increase" + " Register a TypeAdapter for the declaring type, adjust the access filter or increase"
+ " the visibility of the element and its declaring type.", + " the visibility of the element and its declaring type.");
expected.getMessage()
);
} }
} }
@ -196,21 +186,18 @@ public class ReflectionAccessFilterTest {
gson.toJson(new SuperTestClass()); gson.toJson(new SuperTestClass());
fail(); fail();
} catch (JsonIOException expected) { } catch (JsonIOException expected) {
assertEquals( assertThat(expected).hasMessageThat().isEqualTo("ReflectionAccessFilter does not permit using reflection for class"
"ReflectionAccessFilter does not permit using reflection for class"
+ " com.google.gson.functional.ReflectionAccessFilterTest$SuperTestClass." + " com.google.gson.functional.ReflectionAccessFilterTest$SuperTestClass."
+ " Register a TypeAdapter for this type or adjust the access filter.", + " Register a TypeAdapter for this type or adjust the access filter.");
expected.getMessage()
);
} }
// But registration order is reversed, so filter for SubTestClass allows reflection // But registration order is reversed, so filter for SubTestClass allows reflection
String json = gson.toJson(new SubTestClass()); String json = gson.toJson(new SubTestClass());
assertEquals("{\"i\":1}", json); assertThat(json).isEqualTo("{\"i\":1}");
// And unrelated class should not be affected // And unrelated class should not be affected
json = gson.toJson(new OtherClass()); json = gson.toJson(new OtherClass());
assertEquals("{\"i\":2}", json); assertThat(json).isEqualTo("{\"i\":2}");
} }
private static class ClassWithPrivateField { private static class ClassWithPrivateField {
@ -235,13 +222,10 @@ public class ReflectionAccessFilterTest {
gson.toJson(new ExtendingClassWithPrivateField()); gson.toJson(new ExtendingClassWithPrivateField());
fail("Expected exception; test needs to be run with Java >= 9"); fail("Expected exception; test needs to be run with Java >= 9");
} catch (JsonIOException expected) { } catch (JsonIOException expected) {
assertEquals( assertThat(expected).hasMessageThat().isEqualTo("Field 'com.google.gson.functional.ReflectionAccessFilterTest$ClassWithPrivateField#i'"
"Field 'com.google.gson.functional.ReflectionAccessFilterTest$ClassWithPrivateField#i'"
+ " is not accessible and ReflectionAccessFilter does not permit making it accessible." + " is not accessible and ReflectionAccessFilter does not permit making it accessible."
+ " Register a TypeAdapter for the declaring type, adjust the access filter or increase" + " Register a TypeAdapter for the declaring type, adjust the access filter or increase"
+ " the visibility of the element and its declaring type.", + " the visibility of the element and its declaring type.");
expected.getMessage()
);
} }
gson = gson.newBuilder() gson = gson.newBuilder()
@ -255,7 +239,7 @@ public class ReflectionAccessFilterTest {
// Inherited (inaccessible) private field should have been made accessible // Inherited (inaccessible) private field should have been made accessible
String json = gson.toJson(new ExtendingClassWithPrivateField()); String json = gson.toJson(new ExtendingClassWithPrivateField());
assertEquals("{\"i\":1}", json); assertThat(json).isEqualTo("{\"i\":1}");
} }
private static class ClassWithPrivateNoArgsConstructor { private static class ClassWithPrivateNoArgsConstructor {
@ -277,12 +261,9 @@ public class ReflectionAccessFilterTest {
gson.fromJson("{}", ClassWithPrivateNoArgsConstructor.class); gson.fromJson("{}", ClassWithPrivateNoArgsConstructor.class);
fail("Expected exception; test needs to be run with Java >= 9"); fail("Expected exception; test needs to be run with Java >= 9");
} catch (JsonIOException expected) { } catch (JsonIOException expected) {
assertEquals( assertThat(expected).hasMessageThat().isEqualTo("Unable to invoke no-args constructor of class com.google.gson.functional.ReflectionAccessFilterTest$ClassWithPrivateNoArgsConstructor;"
"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" + " 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.", + " InstanceCreator or a TypeAdapter for this type, change the visibility of the constructor or adjust the access filter.");
expected.getMessage()
);
} }
} }
@ -309,12 +290,9 @@ public class ReflectionAccessFilterTest {
gson.fromJson("{}", ClassWithoutNoArgsConstructor.class); gson.fromJson("{}", ClassWithoutNoArgsConstructor.class);
fail(); fail();
} catch (JsonIOException expected) { } catch (JsonIOException expected) {
assertEquals( assertThat(expected).hasMessageThat().isEqualTo("Unable to create instance of class com.google.gson.functional.ReflectionAccessFilterTest$ClassWithoutNoArgsConstructor;"
"Unable to create instance of class com.google.gson.functional.ReflectionAccessFilterTest$ClassWithoutNoArgsConstructor;"
+ " ReflectionAccessFilter does not permit using reflection or Unsafe. Register an InstanceCreator" + " 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.", + " or a TypeAdapter for this type or adjust the access filter to allow using reflection.");
expected.getMessage()
);
} }
// But should not fail when custom TypeAdapter is specified // But should not fail when custom TypeAdapter is specified
@ -324,13 +302,13 @@ public class ReflectionAccessFilterTest {
in.skipValue(); in.skipValue();
return new ClassWithoutNoArgsConstructor("TypeAdapter"); 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"); throw new AssertionError("Not needed for test");
} }
}) })
.create(); .create();
ClassWithoutNoArgsConstructor deserialized = gson.fromJson("{}", ClassWithoutNoArgsConstructor.class); ClassWithoutNoArgsConstructor deserialized = gson.fromJson("{}", ClassWithoutNoArgsConstructor.class);
assertEquals("TypeAdapter", deserialized.s); assertThat(deserialized.s).isEqualTo("TypeAdapter");
// But should not fail when custom InstanceCreator is specified // But should not fail when custom InstanceCreator is specified
gson = gsonBuilder gson = gsonBuilder
@ -341,7 +319,7 @@ public class ReflectionAccessFilterTest {
}) })
.create(); .create();
deserialized = gson.fromJson("{}", ClassWithoutNoArgsConstructor.class); deserialized = gson.fromJson("{}", ClassWithoutNoArgsConstructor.class);
assertEquals("InstanceCreator", deserialized.s); assertThat(deserialized.s).isEqualTo("InstanceCreator");
} }
/** /**
@ -364,18 +342,15 @@ public class ReflectionAccessFilterTest {
.create(); .create();
String json = gson.toJson(new OtherClass()); String json = gson.toJson(new OtherClass());
assertEquals("123", json); assertThat(json).isEqualTo("123");
// But deserialization should fail // But deserialization should fail
try { try {
gson.fromJson("{}", OtherClass.class); gson.fromJson("{}", OtherClass.class);
fail(); fail();
} catch (JsonIOException expected) { } catch (JsonIOException expected) {
assertEquals( assertThat(expected).hasMessageThat().isEqualTo("ReflectionAccessFilter does not permit using reflection for class com.google.gson.functional.ReflectionAccessFilterTest$OtherClass."
"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.");
+ " Register a TypeAdapter for this type or adjust the access filter.",
expected.getMessage()
);
} }
} }
@ -393,7 +368,7 @@ public class ReflectionAccessFilterTest {
}) })
.create(); .create();
List<?> deserialized = gson.fromJson("[1.0]", List.class); 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 class ReflectionAccessFilterTest {
}) })
.create(); .create();
List<?> deserialized = gson.fromJson("[1.0]", LinkedList.class); 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 class ReflectionAccessFilterTest {
gson.fromJson("{}", Runnable.class); gson.fromJson("{}", Runnable.class);
fail(); fail();
} catch (JsonIOException expected) { } catch (JsonIOException expected) {
assertEquals( assertThat(expected).hasMessageThat().isEqualTo("Interfaces can't be instantiated! Register an InstanceCreator or a TypeAdapter for"
"Interfaces can't be instantiated! Register an InstanceCreator or a TypeAdapter for" + " this type. Interface name: java.lang.Runnable");
+ " this type. Interface name: java.lang.Runnable",
expected.getMessage()
);
} }
} }
} }

View File

@ -1,8 +1,6 @@
package com.google.gson.functional; package com.google.gson.functional;
import static org.junit.Assert.assertEquals; import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import com.google.gson.Gson; import com.google.gson.Gson;
@ -65,7 +63,7 @@ public class ReflectionAccessTest {
gson.getAdapter(clazz); gson.getAdapter(clazz);
fail(); fail();
} catch (SecurityException e) { } catch (SecurityException e) {
assertEquals("Gson: no-member-access", e.getMessage()); assertThat(e.getMessage()).isEqualTo("Gson: no-member-access");
} }
final AtomicBoolean wasReadCalled = new AtomicBoolean(false); final AtomicBoolean wasReadCalled = new AtomicBoolean(false);
@ -85,9 +83,9 @@ public class ReflectionAccessTest {
) )
.create(); .create();
assertEquals("\"custom-write\"", gson.toJson(null, clazz)); assertThat(gson.toJson(null, clazz)).isEqualTo("\"custom-write\"");
assertNull(gson.fromJson("{}", clazz)); assertThat(gson.fromJson("{}", clazz)).isNull();
assertTrue(wasReadCalled.get()); assertThat(wasReadCalled.get()).isTrue();
} finally { } finally {
System.setSecurityManager(original); System.setSecurityManager(original);
} }
@ -108,7 +106,7 @@ public class ReflectionAccessTest {
public void testSerializeInternalImplementationObject() { public void testSerializeInternalImplementationObject() {
Gson gson = new Gson(); Gson gson = new Gson();
String json = gson.toJson(Collections.emptyList()); String json = gson.toJson(Collections.emptyList());
assertEquals("[]", json); assertThat(json).isEqualTo("[]");
// But deserialization should fail // But deserialization should fail
Class<?> internalClass = Collections.emptyList().getClass(); Class<?> internalClass = Collections.emptyList().getClass();
@ -118,10 +116,8 @@ public class ReflectionAccessTest {
} catch (JsonSyntaxException e) { } catch (JsonSyntaxException e) {
fail("Unexpected exception; test has to be run with `--illegal-access=deny`"); fail("Unexpected exception; test has to be run with `--illegal-access=deny`");
} catch (JsonIOException expected) { } catch (JsonIOException expected) {
assertTrue(expected.getMessage().startsWith( assertThat(expected).hasMessageThat().startsWith("Failed making constructor 'java.util.Collections$EmptyList()' accessible;"
"Failed making constructor 'java.util.Collections$EmptyList()' accessible;" + " either increase its visibility or write a custom InstanceCreator or TypeAdapter for its declaring type: ");
+ " either increase its visibility or write a custom InstanceCreator or TypeAdapter for its declaring type: "
));
} }
} }
} }

View File

@ -1,8 +1,6 @@
package com.google.gson.functional; package com.google.gson.functional;
import static org.junit.Assert.assertEquals; import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;
@ -31,14 +29,14 @@ public class ReusedTypeVariablesFullyResolveTest {
public void testGenericsPreservation() { public void testGenericsPreservation() {
TestEnumSetCollection withSet = gson.fromJson("{\"collection\":[\"ONE\",\"THREE\"]}", TestEnumSetCollection.class); TestEnumSetCollection withSet = gson.fromJson("{\"collection\":[\"ONE\",\"THREE\"]}", TestEnumSetCollection.class);
Iterator<TestEnum> iterator = withSet.collection.iterator(); Iterator<TestEnum> iterator = withSet.collection.iterator();
assertNotNull(withSet); assertThat(withSet).isNotNull();
assertNotNull(withSet.collection); assertThat(withSet.collection).isNotNull();
assertEquals(2, withSet.collection.size()); assertThat(withSet.collection).hasSize(2);
TestEnum first = iterator.next(); TestEnum first = iterator.next();
TestEnum second = iterator.next(); TestEnum second = iterator.next();
assertTrue(first instanceof TestEnum); assertThat(first).isInstanceOf(TestEnum.class);
assertTrue(second instanceof TestEnum); assertThat(second).isInstanceOf(TestEnum.class);
} }
enum TestEnum { ONE, TWO, THREE } enum TestEnum { ONE, TWO, THREE }

View File

@ -15,7 +15,7 @@
*/ */
package com.google.gson.functional; 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.Gson;
import com.google.gson.JsonElement; import com.google.gson.JsonElement;
@ -46,17 +46,17 @@ public final class RuntimeTypeAdapterFactoryFunctionalTest {
* work correctly for {@link Gson#getDelegateAdapter(TypeAdapterFactory, TypeToken)}. * work correctly for {@link Gson#getDelegateAdapter(TypeAdapterFactory, TypeToken)}.
*/ */
@Test @Test
public void testSubclassesAutomaticallySerialized() throws Exception { public void testSubclassesAutomaticallySerialized() {
Shape shape = new Circle(25); Shape shape = new Circle(25);
String json = gson.toJson(shape); String json = gson.toJson(shape);
shape = gson.fromJson(json, Shape.class); shape = gson.fromJson(json, Shape.class);
assertEquals(25, ((Circle)shape).radius); assertThat(((Circle)shape).radius).isEqualTo(25);
shape = new Square(15); shape = new Square(15);
json = gson.toJson(shape); json = gson.toJson(shape);
shape = gson.fromJson(json, Shape.class); shape = gson.fromJson(json, Shape.class);
assertEquals(15, ((Square)shape).side); assertThat(((Square)shape).side).isEqualTo(15);
assertEquals(ShapeType.SQUARE, shape.type); assertThat(shape.type).isEqualTo(ShapeType.SQUARE);
} }
@JsonAdapter(Shape.JsonAdapterFactory.class) @JsonAdapter(Shape.JsonAdapterFactory.class)
@ -161,7 +161,7 @@ public final class RuntimeTypeAdapterFactoryFunctionalTest {
} }
return new TypeAdapter<R>() { return new TypeAdapter<R>() {
@Override public R read(JsonReader in) throws IOException { @Override public R read(JsonReader in) {
JsonElement jsonElement = Streams.parse(in); JsonElement jsonElement = Streams.parse(in);
JsonElement labelJsonElement = jsonElement.getAsJsonObject().get(typeFieldName); JsonElement labelJsonElement = jsonElement.getAsJsonObject().get(typeFieldName);
if (labelJsonElement == null) { if (labelJsonElement == null) {

View File

@ -16,8 +16,7 @@
package com.google.gson.functional; package com.google.gson.functional;
import static org.junit.Assert.assertEquals; import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertTrue;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;
@ -47,7 +46,7 @@ public class SecurityTest {
public void testNonExecutableJsonSerialization() { public void testNonExecutableJsonSerialization() {
Gson gson = gsonBuilder.generateNonExecutableJson().create(); Gson gson = gsonBuilder.generateNonExecutableJson().create();
String json = gson.toJson(new BagOfPrimitives()); String json = gson.toJson(new BagOfPrimitives());
assertTrue(json.startsWith(JSON_NON_EXECUTABLE_PREFIX)); assertThat(json.startsWith(JSON_NON_EXECUTABLE_PREFIX)).isTrue();
} }
@Test @Test
@ -55,14 +54,14 @@ public class SecurityTest {
String json = JSON_NON_EXECUTABLE_PREFIX + "{longValue:1}"; String json = JSON_NON_EXECUTABLE_PREFIX + "{longValue:1}";
Gson gson = gsonBuilder.create(); Gson gson = gsonBuilder.create();
BagOfPrimitives target = gson.fromJson(json, BagOfPrimitives.class); BagOfPrimitives target = gson.fromJson(json, BagOfPrimitives.class);
assertEquals(1, target.longValue); assertThat(target.longValue).isEqualTo(1);
} }
@Test @Test
public void testJsonWithNonExectuableTokenSerialization() { public void testJsonWithNonExectuableTokenSerialization() {
Gson gson = gsonBuilder.generateNonExecutableJson().create(); Gson gson = gsonBuilder.generateNonExecutableJson().create();
String json = gson.toJson(JSON_NON_EXECUTABLE_PREFIX); String json = gson.toJson(JSON_NON_EXECUTABLE_PREFIX);
assertTrue(json.contains(")]}'\n")); assertThat(json).contains(")]}'\n");
} }
/** /**
@ -74,7 +73,7 @@ public class SecurityTest {
Gson gson = gsonBuilder.create(); Gson gson = gsonBuilder.create();
String json = JSON_NON_EXECUTABLE_PREFIX + "{stringValue:')]}\\u0027\\n'}"; String json = JSON_NON_EXECUTABLE_PREFIX + "{stringValue:')]}\\u0027\\n'}";
BagOfPrimitives target = gson.fromJson(json, BagOfPrimitives.class); BagOfPrimitives target = gson.fromJson(json, BagOfPrimitives.class);
assertEquals(")]}'\n", target.stringValue); assertThat(target.stringValue).isEqualTo(")]}'\n");
} }
/** /**
@ -87,7 +86,7 @@ public class SecurityTest {
Gson gson = gsonBuilder.generateNonExecutableJson().create(); Gson gson = gsonBuilder.generateNonExecutableJson().create();
String json = JSON_NON_EXECUTABLE_PREFIX + "{intValue:2,stringValue:')]}\\u0027\\n'}"; String json = JSON_NON_EXECUTABLE_PREFIX + "{intValue:2,stringValue:')]}\\u0027\\n'}";
BagOfPrimitives target = gson.fromJson(json, BagOfPrimitives.class); BagOfPrimitives target = gson.fromJson(json, BagOfPrimitives.class);
assertEquals(")]}'\n", target.stringValue); assertThat(target.stringValue).isEqualTo(")]}'\n");
assertEquals(2, target.intValue); assertThat(target.intValue).isEqualTo(2);
} }
} }

View File

@ -15,7 +15,7 @@
*/ */
package com.google.gson.functional; 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.Gson;
import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.SerializedName;
@ -28,23 +28,23 @@ public final class SerializedNameTest {
public void testFirstNameIsChosenForSerialization() { public void testFirstNameIsChosenForSerialization() {
MyClass target = new MyClass("v1", "v2"); MyClass target = new MyClass("v1", "v2");
// Ensure name1 occurs exactly once, and name2 and name3 don't appear // 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 @Test
public void testMultipleNamesDeserializedCorrectly() { 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 // Both name1 and name2 gets deserialized to b
assertEquals("v11", gson.fromJson("{'name1':'v11'}", MyClass.class).b); assertThat(gson.fromJson("{'name1':'v11'}", MyClass.class).b).isEqualTo("v11");
assertEquals("v2", gson.fromJson("{'name2':'v2'}", MyClass.class).b); assertThat(gson.fromJson("{'name2':'v2'}", MyClass.class).b).isEqualTo("v2");
assertEquals("v3", gson.fromJson("{'name3':'v3'}", MyClass.class).b); assertThat(gson.fromJson("{'name3':'v3'}", MyClass.class).b).isEqualTo("v3");
} }
@Test @Test
public void testMultipleNamesInTheSameString() { public void testMultipleNamesInTheSameString() {
// The last value takes precedence // 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 { private static final class MyClass {

View File

@ -16,9 +16,8 @@
package com.google.gson.functional; package com.google.gson.functional;
import static org.junit.Assert.assertEquals; import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertNull; import static com.google.common.truth.Truth.assertWithMessage;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import com.google.gson.Gson; import com.google.gson.Gson;
@ -52,9 +51,9 @@ public final class StreamingTypeAdaptersTest {
truck.passengers = Arrays.asList(new Person("Jesse", 29), new Person("Jodie", 29)); truck.passengers = Arrays.asList(new Person("Jesse", 29), new Person("Jodie", 29));
truck.horsePower = 300; truck.horsePower = 300;
assertEquals("{'horsePower':300.0," assertThat(truckAdapter.toJson(truck).replace('\"', '\''))
+ "'passengers':[{'age':29,'name':'Jesse'},{'age':29,'name':'Jodie'}]}", .isEqualTo("{'horsePower':300.0,"
truckAdapter.toJson(truck).replace('\"', '\'')); + "'passengers':[{'age':29,'name':'Jesse'},{'age':29,'name':'Jodie'}]}");
} }
@Test @Test
@ -62,36 +61,37 @@ public final class StreamingTypeAdaptersTest {
String json = "{'horsePower':300.0," String json = "{'horsePower':300.0,"
+ "'passengers':[{'age':29,'name':'Jesse'},{'age':29,'name':'Jodie'}]}"; + "'passengers':[{'age':29,'name':'Jesse'},{'age':29,'name':'Jodie'}]}";
Truck truck = truckAdapter.fromJson(json.replace('\'', '\"')); Truck truck = truckAdapter.fromJson(json.replace('\'', '\"'));
assertEquals(300.0, truck.horsePower, 0); assertThat(truck.horsePower).isEqualTo(300.0);
assertEquals(Arrays.asList(new Person("Jesse", 29), new Person("Jodie", 29)), truck.passengers); assertThat(truck.passengers)
.isEqualTo(Arrays.asList(new Person("Jesse", 29), new Person("Jodie", 29)));
} }
@Test @Test
public void testSerializeNullField() { public void testSerializeNullField() {
Truck truck = new Truck(); Truck truck = new Truck();
truck.passengers = null; truck.passengers = null;
assertEquals("{'horsePower':0.0,'passengers':null}", assertThat(truckAdapter.toJson(truck).replace('\"', '\''))
truckAdapter.toJson(truck).replace('\"', '\'')); .isEqualTo("{'horsePower':0.0,'passengers':null}");
} }
@Test @Test
public void testDeserializeNullField() throws IOException { public void testDeserializeNullField() throws IOException {
Truck truck = truckAdapter.fromJson("{'horsePower':0.0,'passengers':null}".replace('\'', '\"')); Truck truck = truckAdapter.fromJson("{'horsePower':0.0,'passengers':null}".replace('\'', '\"'));
assertNull(truck.passengers); assertThat(truck.passengers).isNull();
} }
@Test @Test
public void testSerializeNullObject() { public void testSerializeNullObject() {
Truck truck = new Truck(); Truck truck = new Truck();
truck.passengers = Arrays.asList((Person) null); truck.passengers = Arrays.asList((Person) null);
assertEquals("{'horsePower':0.0,'passengers':[null]}", assertThat(truckAdapter.toJson(truck).replace('\"', '\''))
truckAdapter.toJson(truck).replace('\"', '\'')); .isEqualTo("{'horsePower':0.0,'passengers':[null]}");
} }
@Test @Test
public void testDeserializeNullObject() throws IOException { public void testDeserializeNullObject() throws IOException {
Truck truck = truckAdapter.fromJson("{'horsePower':0.0,'passengers':[null]}".replace('\'', '\"')); 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 @Test
@ -99,15 +99,15 @@ public final class StreamingTypeAdaptersTest {
usePersonNameAdapter(); usePersonNameAdapter();
Truck truck = new Truck(); Truck truck = new Truck();
truck.passengers = Arrays.asList(new Person("Jesse", 29), new Person("Jodie", 29)); truck.passengers = Arrays.asList(new Person("Jesse", 29), new Person("Jodie", 29));
assertEquals("{'horsePower':0.0,'passengers':['Jesse','Jodie']}", assertThat(truckAdapter.toJson(truck).replace('\"', '\''))
truckAdapter.toJson(truck).replace('\"', '\'')); .isEqualTo("{'horsePower':0.0,'passengers':['Jesse','Jodie']}");
} }
@Test @Test
public void testDeserializeWithCustomTypeAdapter() throws IOException { public void testDeserializeWithCustomTypeAdapter() throws IOException {
usePersonNameAdapter(); usePersonNameAdapter();
Truck truck = truckAdapter.fromJson("{'horsePower':0.0,'passengers':['Jesse','Jodie']}".replace('\'', '\"')); 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() { private void usePersonNameAdapter() {
@ -129,7 +129,7 @@ public final class StreamingTypeAdaptersTest {
Map<String, Double> map = new LinkedHashMap<>(); Map<String, Double> map = new LinkedHashMap<>();
map.put("a", 5.0); map.put("a", 5.0);
map.put("b", 10.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 @Test
@ -137,27 +137,27 @@ public final class StreamingTypeAdaptersTest {
Map<String, Double> map = new LinkedHashMap<>(); Map<String, Double> map = new LinkedHashMap<>();
map.put("a", 5.0); map.put("a", 5.0);
map.put("b", 10.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 @Test
public void testSerialize1dArray() { public void testSerialize1dArray() {
TypeAdapter<double[]> arrayAdapter = miniGson.getAdapter(new TypeToken<double[]>() {}); TypeAdapter<double[]> arrayAdapter = miniGson.getAdapter(new TypeToken<double[]>() {});
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 @Test
public void testDeserialize1dArray() throws IOException { public void testDeserialize1dArray() throws IOException {
TypeAdapter<double[]> arrayAdapter = miniGson.getAdapter(new TypeToken<double[]>() {}); TypeAdapter<double[]> arrayAdapter = miniGson.getAdapter(new TypeToken<double[]>() {});
double[] array = arrayAdapter.fromJson("[1.0,2.0,3.0]"); 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 @Test
public void testSerialize2dArray() { public void testSerialize2dArray() {
TypeAdapter<double[][]> arrayAdapter = miniGson.getAdapter(new TypeToken<double[][]>() {}); TypeAdapter<double[][]> arrayAdapter = miniGson.getAdapter(new TypeToken<double[][]>() {});
double[][] array = { {1.0, 2.0 }, { 3.0 } }; 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 @Test
@ -165,7 +165,7 @@ public final class StreamingTypeAdaptersTest {
TypeAdapter<double[][]> arrayAdapter = miniGson.getAdapter(new TypeToken<double[][]>() {}); TypeAdapter<double[][]> arrayAdapter = miniGson.getAdapter(new TypeToken<double[][]>() {});
double[][] array = arrayAdapter.fromJson("[[1.0,2.0],[3.0]]"); double[][] array = arrayAdapter.fromJson("[[1.0,2.0],[3.0]]");
double[][] expected = { {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 @Test
@ -196,12 +196,12 @@ public final class StreamingTypeAdaptersTest {
fail(); fail();
} catch (JsonSyntaxException expected) {} } catch (JsonSyntaxException expected) {}
gson = new GsonBuilder().registerTypeAdapter(Person.class, typeAdapter.nullSafe()).create(); gson = new GsonBuilder().registerTypeAdapter(Person.class, typeAdapter.nullSafe()).create();
assertEquals("{\"horsePower\":1.0,\"passengers\":[null,\"jesse,30\"]}", assertThat(gson.toJson(truck, Truck.class))
gson.toJson(truck, Truck.class)); .isEqualTo("{\"horsePower\":1.0,\"passengers\":[null,\"jesse,30\"]}");
truck = gson.fromJson(json, Truck.class); truck = gson.fromJson(json, Truck.class);
assertEquals(1.0D, truck.horsePower, 0); assertThat(truck.horsePower).isEqualTo(1.0D);
assertNull(truck.passengers.get(0)); assertThat(truck.passengers.get(0)).isNull();
assertEquals("jesse", truck.passengers.get(1).name); assertThat(truck.passengers.get(1).name).isEqualTo("jesse");
} }
@Test @Test
@ -210,10 +210,10 @@ public final class StreamingTypeAdaptersTest {
Node root = new Node("root"); Node root = new Node("root");
root.left = new Node("left"); root.left = new Node("left");
root.right = new Node("right"); root.right = new Node("right");
assertEquals("{'label':'root'," assertThat(nodeAdapter.toJson(root).replace('"', '\''))
.isEqualTo("{'label':'root',"
+ "'left':{'label':'left','left':null,'right':null}," + "'left':{'label':'left','left':null,'right':null},"
+ "'right':{'label':'right','left':null,'right':null}}", + "'right':{'label':'right','left':null,'right':null}}");
nodeAdapter.toJson(root).replace('"', '\''));
} }
@Test @Test
@ -228,8 +228,8 @@ public final class StreamingTypeAdaptersTest {
truckObject.add("passengers", passengersArray); truckObject.add("passengers", passengersArray);
Truck truck = truckAdapter.fromJsonTree(truckObject); Truck truck = truckAdapter.fromJsonTree(truckObject);
assertEquals(300.0, truck.horsePower, 0); assertThat(truck.horsePower).isEqualTo(300.0);
assertEquals(Arrays.asList(new Person("Jesse", 30)), truck.passengers); assertThat(truck.passengers).isEqualTo(Arrays.asList(new Person("Jesse", 30)));
} }
static class Truck { static class Truck {

View File

@ -1,6 +1,6 @@
package com.google.gson.functional; 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.Gson;
import org.junit.Before; import org.junit.Before;
@ -21,94 +21,94 @@ public class StringTest {
} }
@Test @Test
public void testStringValueSerialization() throws Exception { public void testStringValueSerialization() {
String value = "someRandomStringValue"; String value = "someRandomStringValue";
assertEquals('"' + value + '"', gson.toJson(value)); assertThat(gson.toJson(value)).isEqualTo('"' + value + '"');
} }
@Test @Test
public void testStringValueDeserialization() throws Exception { public void testStringValueDeserialization() {
String value = "someRandomStringValue"; String value = "someRandomStringValue";
String actual = gson.fromJson("\"" + value + "\"", String.class); String actual = gson.fromJson("\"" + value + "\"", String.class);
assertEquals(value, actual); assertThat(actual).isEqualTo(value);
} }
@Test @Test
public void testSingleQuoteInStringSerialization() throws Exception { public void testSingleQuoteInStringSerialization() {
String valueWithQuotes = "beforeQuote'afterQuote"; String valueWithQuotes = "beforeQuote'afterQuote";
String jsonRepresentation = gson.toJson(valueWithQuotes); String jsonRepresentation = gson.toJson(valueWithQuotes);
assertEquals(valueWithQuotes, gson.fromJson(jsonRepresentation, String.class)); assertThat(gson.fromJson(jsonRepresentation, String.class)).isEqualTo(valueWithQuotes);
} }
@Test @Test
public void testEscapedCtrlNInStringSerialization() throws Exception { public void testEscapedCtrlNInStringSerialization() {
String value = "a\nb"; String value = "a\nb";
String json = gson.toJson(value); String json = gson.toJson(value);
assertEquals("\"a\\nb\"", json); assertThat(json).isEqualTo("\"a\\nb\"");
} }
@Test @Test
public void testEscapedCtrlNInStringDeserialization() throws Exception { public void testEscapedCtrlNInStringDeserialization() {
String json = "'a\\nb'"; String json = "'a\\nb'";
String actual = gson.fromJson(json, String.class); String actual = gson.fromJson(json, String.class);
assertEquals("a\nb", actual); assertThat(actual).isEqualTo("a\nb");
} }
@Test @Test
public void testEscapedCtrlRInStringSerialization() throws Exception { public void testEscapedCtrlRInStringSerialization() {
String value = "a\rb"; String value = "a\rb";
String json = gson.toJson(value); String json = gson.toJson(value);
assertEquals("\"a\\rb\"", json); assertThat(json).isEqualTo("\"a\\rb\"");
} }
@Test @Test
public void testEscapedCtrlRInStringDeserialization() throws Exception { public void testEscapedCtrlRInStringDeserialization() {
String json = "'a\\rb'"; String json = "'a\\rb'";
String actual = gson.fromJson(json, String.class); String actual = gson.fromJson(json, String.class);
assertEquals("a\rb", actual); assertThat(actual).isEqualTo("a\rb");
} }
@Test @Test
public void testEscapedBackslashInStringSerialization() throws Exception { public void testEscapedBackslashInStringSerialization() {
String value = "a\\b"; String value = "a\\b";
String json = gson.toJson(value); String json = gson.toJson(value);
assertEquals("\"a\\\\b\"", json); assertThat(json).isEqualTo("\"a\\\\b\"");
} }
@Test @Test
public void testEscapedBackslashInStringDeserialization() throws Exception { public void testEscapedBackslashInStringDeserialization() {
String actual = gson.fromJson("'a\\\\b'", String.class); String actual = gson.fromJson("'a\\\\b'", String.class);
assertEquals("a\\b", actual); assertThat(actual).isEqualTo("a\\b");
} }
@Test @Test
public void testSingleQuoteInStringDeserialization() throws Exception { public void testSingleQuoteInStringDeserialization() {
String value = "beforeQuote'afterQuote"; String value = "beforeQuote'afterQuote";
String actual = gson.fromJson("\"" + value + "\"", String.class); String actual = gson.fromJson("\"" + value + "\"", String.class);
assertEquals(value, actual); assertThat(actual).isEqualTo(value);
} }
@Test @Test
public void testEscapingQuotesInStringSerialization() throws Exception { public void testEscapingQuotesInStringSerialization() {
String valueWithQuotes = "beforeQuote\"afterQuote"; String valueWithQuotes = "beforeQuote\"afterQuote";
String jsonRepresentation = gson.toJson(valueWithQuotes); String jsonRepresentation = gson.toJson(valueWithQuotes);
String target = gson.fromJson(jsonRepresentation, String.class); String target = gson.fromJson(jsonRepresentation, String.class);
assertEquals(valueWithQuotes, target); assertThat(target).isEqualTo(valueWithQuotes);
} }
@Test @Test
public void testEscapingQuotesInStringDeserialization() throws Exception { public void testEscapingQuotesInStringDeserialization() {
String value = "beforeQuote\\\"afterQuote"; String value = "beforeQuote\\\"afterQuote";
String actual = gson.fromJson("\"" + value + "\"", String.class); String actual = gson.fromJson("\"" + value + "\"", String.class);
String expected = "beforeQuote\"afterQuote"; String expected = "beforeQuote\"afterQuote";
assertEquals(expected, actual); assertThat(actual).isEqualTo(expected);
} }
@Test @Test
public void testStringValueAsSingleElementArraySerialization() throws Exception { public void testStringValueAsSingleElementArraySerialization() {
String[] target = {"abc"}; String[] target = {"abc"};
assertEquals("[\"abc\"]", gson.toJson(target)); assertThat(gson.toJson(target)).isEqualTo("[\"abc\"]");
assertEquals("[\"abc\"]", gson.toJson(target, String[].class)); assertThat(gson.toJson(target, String[].class)).isEqualTo("[\"abc\"]");
} }
@Test @Test
@ -116,7 +116,7 @@ public class StringTest {
String value = "/"; String value = "/";
String json = "'\\/'"; String json = "'\\/'";
String actual = gson.fromJson(json, String.class); String actual = gson.fromJson(json, String.class);
assertEquals(value, actual); assertThat(actual).isEqualTo(value);
} }
/** /**
@ -126,7 +126,7 @@ public class StringTest {
public void testAssignmentCharSerialization() { public void testAssignmentCharSerialization() {
String value = "abc="; String value = "abc=";
String json = gson.toJson(value); String json = gson.toJson(value);
assertEquals("\"abc\\u003d\"", json); assertThat(json).isEqualTo("\"abc\\u003d\"");
} }
/** /**
@ -136,24 +136,24 @@ public class StringTest {
public void testAssignmentCharDeserialization() { public void testAssignmentCharDeserialization() {
String json = "\"abc=\""; String json = "\"abc=\"";
String value = gson.fromJson(json, String.class); String value = gson.fromJson(json, String.class);
assertEquals("abc=", value); assertThat(value).isEqualTo("abc=");
json = "'abc\u003d'"; json = "'abc\u003d'";
value = gson.fromJson(json, String.class); value = gson.fromJson(json, String.class);
assertEquals("abc=", value); assertThat(value).isEqualTo("abc=");
} }
@Test @Test
public void testJavascriptKeywordsInStringSerialization() { public void testJavascriptKeywordsInStringSerialization() {
String value = "null true false function"; String value = "null true false function";
String json = gson.toJson(value); String json = gson.toJson(value);
assertEquals("\"" + value + "\"", json); assertThat(json).isEqualTo("\"" + value + "\"");
} }
@Test @Test
public void testJavascriptKeywordsInStringDeserialization() { public void testJavascriptKeywordsInStringDeserialization() {
String json = "'null true false function'"; String json = "'null true false function'";
String value = gson.fromJson(json, String.class); String value = gson.fromJson(json, String.class);
assertEquals(json.substring(1, json.length() - 1), value); assertThat(json.substring(1, json.length() - 1)).isEqualTo(value);
} }
} }

View File

@ -16,7 +16,7 @@
package com.google.gson.functional; 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.Assert.fail;
import com.google.gson.Gson; import com.google.gson.Gson;
@ -28,7 +28,6 @@ import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonReader;
import java.lang.reflect.Type; import java.lang.reflect.Type;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Collection; import java.util.Collection;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.List; import java.util.List;
@ -38,10 +37,10 @@ public class ToNumberPolicyFunctionalTest {
@Test @Test
public void testDefault() { public void testDefault() {
Gson gson = new Gson(); Gson gson = new Gson();
assertEquals(null, gson.fromJson("null", Object.class)); assertThat(gson.fromJson("null", Object.class)).isEqualTo(null);
assertEquals(10D, gson.fromJson("10", Object.class)); assertThat(gson.fromJson("10", Object.class)).isEqualTo(10D);
assertEquals(null, gson.fromJson("null", Number.class)); assertThat(gson.fromJson("null", Number.class)).isEqualTo(null);
assertEquals(new LazilyParsedNumber("10"), gson.fromJson("10", Number.class)); assertThat(gson.fromJson("10", Number.class)).isEqualTo(new LazilyParsedNumber("10"));
} }
@Test @Test
@ -50,10 +49,10 @@ public class ToNumberPolicyFunctionalTest {
.setObjectToNumberStrategy(ToNumberPolicy.DOUBLE) .setObjectToNumberStrategy(ToNumberPolicy.DOUBLE)
.setNumberToNumberStrategy(ToNumberPolicy.DOUBLE) .setNumberToNumberStrategy(ToNumberPolicy.DOUBLE)
.create(); .create();
assertEquals(null, gson.fromJson("null", Object.class)); assertThat(gson.fromJson("null", Object.class)).isEqualTo(null);
assertEquals(10.0, gson.fromJson("10", Object.class)); assertThat(gson.fromJson("10", Object.class)).isEqualTo(10.0);
assertEquals(null, gson.fromJson("null", Number.class)); assertThat(gson.fromJson("null", Number.class)).isEqualTo(null);
assertEquals(10.0, gson.fromJson("10", Number.class)); assertThat(gson.fromJson("10", Number.class)).isEqualTo(10.0);
} }
@Test @Test
@ -62,10 +61,10 @@ public class ToNumberPolicyFunctionalTest {
.setObjectToNumberStrategy(ToNumberPolicy.LAZILY_PARSED_NUMBER) .setObjectToNumberStrategy(ToNumberPolicy.LAZILY_PARSED_NUMBER)
.setNumberToNumberStrategy(ToNumberPolicy.LAZILY_PARSED_NUMBER) .setNumberToNumberStrategy(ToNumberPolicy.LAZILY_PARSED_NUMBER)
.create(); .create();
assertEquals(null, gson.fromJson("null", Object.class)); assertThat(gson.fromJson("null", Object.class)).isEqualTo(null);
assertEquals(new LazilyParsedNumber("10"), gson.fromJson("10", Object.class)); assertThat(gson.fromJson("10", Object.class)).isEqualTo(new LazilyParsedNumber("10"));
assertEquals(null, gson.fromJson("null", Number.class)); assertThat(gson.fromJson("null", Number.class)).isEqualTo(null);
assertEquals(new LazilyParsedNumber("10"), gson.fromJson("10", Number.class)); assertThat(gson.fromJson("10", Number.class)).isEqualTo(new LazilyParsedNumber("10"));
} }
@Test @Test
@ -74,12 +73,12 @@ public class ToNumberPolicyFunctionalTest {
.setObjectToNumberStrategy(ToNumberPolicy.LONG_OR_DOUBLE) .setObjectToNumberStrategy(ToNumberPolicy.LONG_OR_DOUBLE)
.setNumberToNumberStrategy(ToNumberPolicy.LONG_OR_DOUBLE) .setNumberToNumberStrategy(ToNumberPolicy.LONG_OR_DOUBLE)
.create(); .create();
assertEquals(null, gson.fromJson("null", Object.class)); assertThat(gson.fromJson("null", Object.class)).isEqualTo(null);
assertEquals(10L, gson.fromJson("10", Object.class)); assertThat(gson.fromJson("10", Object.class)).isEqualTo(10L);
assertEquals(10.0, gson.fromJson("10.0", Object.class)); assertThat(gson.fromJson("10.0", Object.class)).isEqualTo(10.0);
assertEquals(null, gson.fromJson("null", Number.class)); assertThat(gson.fromJson("null", Number.class)).isEqualTo(null);
assertEquals(10L, gson.fromJson("10", Number.class)); assertThat(gson.fromJson("10", Number.class)).isEqualTo(10L);
assertEquals(10.0, gson.fromJson("10.0", Number.class)); assertThat(gson.fromJson("10.0", Number.class)).isEqualTo(10.0);
} }
@Test @Test
@ -88,14 +87,14 @@ public class ToNumberPolicyFunctionalTest {
.setObjectToNumberStrategy(ToNumberPolicy.BIG_DECIMAL) .setObjectToNumberStrategy(ToNumberPolicy.BIG_DECIMAL)
.setNumberToNumberStrategy(ToNumberPolicy.BIG_DECIMAL) .setNumberToNumberStrategy(ToNumberPolicy.BIG_DECIMAL)
.create(); .create();
assertEquals(null, gson.fromJson("null", Object.class)); assertThat(gson.fromJson("null", Object.class)).isEqualTo(null);
assertEquals(new BigDecimal("10"), gson.fromJson("10", Object.class)); assertThat(gson.fromJson("10", Object.class)).isEqualTo(new BigDecimal("10"));
assertEquals(new BigDecimal("10.0"), gson.fromJson("10.0", Object.class)); assertThat(gson.fromJson("10.0", Object.class)).isEqualTo(new BigDecimal("10.0"));
assertEquals(null, gson.fromJson("null", Number.class)); assertThat(gson.fromJson("null", Number.class)).isEqualTo(null);
assertEquals(new BigDecimal("10"), gson.fromJson("10", Number.class)); assertThat(gson.fromJson("10", Number.class)).isEqualTo(new BigDecimal("10"));
assertEquals(new BigDecimal("10.0"), gson.fromJson("10.0", Number.class)); assertThat(gson.fromJson("10.0", Number.class)).isEqualTo(new BigDecimal("10.0"));
assertEquals(new BigDecimal("3.141592653589793238462643383279"), gson.fromJson("3.141592653589793238462643383279", BigDecimal.class)); assertThat(gson.fromJson("3.141592653589793238462643383279", BigDecimal.class)).isEqualTo(new BigDecimal("3.141592653589793238462643383279"));
assertEquals(new BigDecimal("1e400"), gson.fromJson("1e400", BigDecimal.class)); assertThat(gson.fromJson("1e400", BigDecimal.class)).isEqualTo(new BigDecimal("1e400"));
} }
@Test @Test
@ -110,10 +109,10 @@ public class ToNumberPolicyFunctionalTest {
expected.add(10.0); expected.add(10.0);
Type objectCollectionType = new TypeToken<Collection<Object>>() { }.getType(); Type objectCollectionType = new TypeToken<Collection<Object>>() { }.getType();
Collection<Object> objects = gson.fromJson("[null,10,10.0]", objectCollectionType); Collection<Object> objects = gson.fromJson("[null,10,10.0]", objectCollectionType);
assertEquals(expected, objects); assertThat(objects).isEqualTo(expected);
Type numberCollectionType = new TypeToken<Collection<Number>>() { }.getType(); Type numberCollectionType = new TypeToken<Collection<Number>>() { }.getType();
Collection<Object> numbers = gson.fromJson("[null,10,10.0]", numberCollectionType); Collection<Object> numbers = gson.fromJson("[null,10,10.0]", numberCollectionType);
assertEquals(expected, numbers); assertThat(numbers).isEqualTo(expected);
} }
@Test @Test
@ -129,7 +128,7 @@ public class ToNumberPolicyFunctionalTest {
.setNumberToNumberStrategy(fail) .setNumberToNumberStrategy(fail)
.create(); .create();
List<Object> numbers = gson.fromJson("[null, 10, 20, 30]", new TypeToken<List<Byte>>() {}.getType()); List<Object> numbers = gson.fromJson("[null, 10, 20, 30]", new TypeToken<List<Byte>>() {}.getType());
assertEquals(Arrays.asList(null, (byte) 10, (byte) 20, (byte) 30), numbers); assertThat(numbers).containsExactly(null, (byte) 10, (byte) 20, (byte) 30).inOrder();
try { try {
gson.fromJson("[null, 10, 20, 30]", new TypeToken<List<Object>>() {}.getType()); gson.fromJson("[null, 10, 20, 30]", new TypeToken<List<Object>>() {}.getType());
fail(); fail();

View File

@ -16,8 +16,7 @@
package com.google.gson.functional; package com.google.gson.functional;
import static org.junit.Assert.assertEquals; import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertTrue;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;
@ -65,9 +64,9 @@ public class TreeTypeAdaptersTest {
@Test @Test
public void testSerializeId() { public void testSerializeId() {
String json = gson.toJson(course, TYPE_COURSE_HISTORY); String json = gson.toJson(course, TYPE_COURSE_HISTORY);
assertTrue(json.contains(String.valueOf(COURSE_ID.getValue()))); assertThat(json).contains(String.valueOf(COURSE_ID.getValue()));
assertTrue(json.contains(String.valueOf(STUDENT1_ID.getValue()))); assertThat(json).contains(String.valueOf(STUDENT1_ID.getValue()));
assertTrue(json.contains(String.valueOf(STUDENT2_ID.getValue()))); assertThat(json).contains(String.valueOf(STUDENT2_ID.getValue()));
} }
@Test @Test
@ -75,9 +74,9 @@ public class TreeTypeAdaptersTest {
String json = "{courseId:1,students:[{id:1,name:'first'},{id:6,name:'second'}]," String json = "{courseId:1,students:[{id:1,name:'first'},{id:6,name:'second'}],"
+ "numAssignments:4,assignment:{}}"; + "numAssignments:4,assignment:{}}";
Course<HistoryCourse> target = gson.fromJson(json, TYPE_COURSE_HISTORY); Course<HistoryCourse> target = gson.fromJson(json, TYPE_COURSE_HISTORY);
assertEquals("1", target.getStudents().get(0).id.getValue()); assertThat(target.getStudents().get(0).id.getValue()).isEqualTo("1");
assertEquals("6", target.getStudents().get(1).id.getValue()); assertThat(target.getStudents().get(1).id.getValue()).isEqualTo("6");
assertEquals("1", target.getId().getValue()); assertThat(target.getId().getValue()).isEqualTo("1");
} }
private static final class Id<R> { private static final class Id<R> {

View File

@ -16,7 +16,7 @@
package com.google.gson.functional; 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.Gson;
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;
@ -42,8 +42,8 @@ public final class TypeAdapterPrecedenceTest {
.registerTypeAdapter(Foo.class, newDeserializer("deserializer 1")) .registerTypeAdapter(Foo.class, newDeserializer("deserializer 1"))
.registerTypeAdapter(Foo.class, newDeserializer("deserializer 2")) .registerTypeAdapter(Foo.class, newDeserializer("deserializer 2"))
.create(); .create();
assertEquals("\"foo via serializer 2\"", gson.toJson(new Foo("foo"))); assertThat(gson.toJson(new Foo("foo"))).isEqualTo("\"foo via serializer 2\"");
assertEquals("foo via deserializer 2", gson.fromJson("foo", Foo.class).name); assertThat(gson.fromJson("foo", Foo.class).name).isEqualTo("foo via deserializer 2");
} }
@Test @Test
@ -52,8 +52,8 @@ public final class TypeAdapterPrecedenceTest {
.registerTypeAdapter(Foo.class, newTypeAdapter("type adapter 1")) .registerTypeAdapter(Foo.class, newTypeAdapter("type adapter 1"))
.registerTypeAdapter(Foo.class, newTypeAdapter("type adapter 2")) .registerTypeAdapter(Foo.class, newTypeAdapter("type adapter 2"))
.create(); .create();
assertEquals("\"foo via type adapter 2\"", gson.toJson(new Foo("foo"))); assertThat(gson.toJson(new Foo("foo"))).isEqualTo("\"foo via type adapter 2\"");
assertEquals("foo via type adapter 2", gson.fromJson("foo", Foo.class).name); assertThat(gson.fromJson("foo", Foo.class).name).isEqualTo("foo via type adapter 2");
} }
@Test @Test
@ -63,8 +63,8 @@ public final class TypeAdapterPrecedenceTest {
.registerTypeAdapter(Foo.class, newDeserializer("deserializer")) .registerTypeAdapter(Foo.class, newDeserializer("deserializer"))
.registerTypeAdapter(Foo.class, newTypeAdapter("type adapter")) .registerTypeAdapter(Foo.class, newTypeAdapter("type adapter"))
.create(); .create();
assertEquals("\"foo via type adapter\"", gson.toJson(new Foo("foo"))); assertThat(gson.toJson(new Foo("foo"))).isEqualTo("\"foo via type adapter\"");
assertEquals("foo via type adapter", gson.fromJson("foo", Foo.class).name); assertThat(gson.fromJson("foo", Foo.class).name).isEqualTo("foo via type adapter");
} }
@Test @Test
@ -74,8 +74,8 @@ public final class TypeAdapterPrecedenceTest {
.registerTypeAdapter(Foo.class, newSerializer("serializer")) .registerTypeAdapter(Foo.class, newSerializer("serializer"))
.registerTypeAdapter(Foo.class, newDeserializer("deserializer")) .registerTypeAdapter(Foo.class, newDeserializer("deserializer"))
.create(); .create();
assertEquals("\"foo via serializer\"", gson.toJson(new Foo("foo"))); assertThat(gson.toJson(new Foo("foo"))).isEqualTo("\"foo via serializer\"");
assertEquals("foo via deserializer", gson.fromJson("foo", Foo.class).name); assertThat( gson.fromJson("foo", Foo.class).name).isEqualTo("foo via deserializer");
} }
@Test @Test
@ -85,8 +85,8 @@ public final class TypeAdapterPrecedenceTest {
.registerTypeAdapter(Foo.class, newSerializer("serializer")) .registerTypeAdapter(Foo.class, newSerializer("serializer"))
.registerTypeAdapter(Foo.class, newDeserializer("deserializer")) .registerTypeAdapter(Foo.class, newDeserializer("deserializer"))
.create(); .create();
assertEquals("\"foo via serializer\"", gson.toJson(new Foo("foo"))); assertThat(gson.toJson(new Foo("foo"))).isEqualTo("\"foo via serializer\"");
assertEquals("foo via deserializer", gson.fromJson("foo", Foo.class).name); assertThat(gson.fromJson("foo", Foo.class).name).isEqualTo("foo via deserializer");
} }
@Test @Test
@ -96,8 +96,8 @@ public final class TypeAdapterPrecedenceTest {
.registerTypeHierarchyAdapter(Foo.class, newSerializer("serializer")) .registerTypeHierarchyAdapter(Foo.class, newSerializer("serializer"))
.registerTypeHierarchyAdapter(Foo.class, newDeserializer("deserializer")) .registerTypeHierarchyAdapter(Foo.class, newDeserializer("deserializer"))
.create(); .create();
assertEquals("\"foo via type adapter\"", gson.toJson(new Foo("foo"))); assertThat(gson.toJson(new Foo("foo"))).isEqualTo("\"foo via type adapter\"");
assertEquals("foo via type adapter", gson.fromJson("foo", Foo.class).name); assertThat(gson.fromJson("foo", Foo.class).name).isEqualTo("foo via type adapter");
} }
@Test @Test
@ -107,8 +107,8 @@ public final class TypeAdapterPrecedenceTest {
.registerTypeHierarchyAdapter(Foo.class, newDeserializer("deserializer")) .registerTypeHierarchyAdapter(Foo.class, newDeserializer("deserializer"))
.registerTypeHierarchyAdapter(Foo.class, newTypeAdapter("type adapter")) .registerTypeHierarchyAdapter(Foo.class, newTypeAdapter("type adapter"))
.create(); .create();
assertEquals("\"foo via type adapter\"", gson.toJson(new Foo("foo"))); assertThat(gson.toJson(new Foo("foo"))).isEqualTo("\"foo via type adapter\"");
assertEquals("foo via type adapter", gson.fromJson("foo", Foo.class).name); assertThat(gson.fromJson("foo", Foo.class).name).isEqualTo("foo via type adapter");
} }
@Test @Test
@ -119,8 +119,8 @@ public final class TypeAdapterPrecedenceTest {
.registerTypeAdapter(Foo.class, newSerializer("non hierarchical")) .registerTypeAdapter(Foo.class, newSerializer("non hierarchical"))
.registerTypeAdapter(Foo.class, newDeserializer("non hierarchical")) .registerTypeAdapter(Foo.class, newDeserializer("non hierarchical"))
.create(); .create();
assertEquals("\"foo via non hierarchical\"", gson.toJson(new Foo("foo"))); assertThat(gson.toJson(new Foo("foo"))).isEqualTo("\"foo via non hierarchical\"");
assertEquals("foo via non hierarchical", gson.fromJson("foo", Foo.class).name); assertThat(gson.fromJson("foo", Foo.class).name).isEqualTo("foo via non hierarchical");
} }
private static class Foo { private static class Foo {

View File

@ -1,6 +1,6 @@
package com.google.gson.functional; 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.Gson;
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;
@ -51,7 +51,7 @@ public class TypeAdapterRuntimeTypeWrapperTest {
.create(); .create();
String json = gson.toJson(new Container()); String json = gson.toJson(new Container());
assertEquals("{\"b\":\"serializer\"}", json); assertThat(json).isEqualTo("{\"b\":\"serializer\"}");
} }
/** /**
@ -66,7 +66,7 @@ public class TypeAdapterRuntimeTypeWrapperTest {
.create(); .create();
String json = gson.toJson(new Container()); String json = gson.toJson(new Container());
assertEquals("{\"b\":{\"f\":\"test\"}}", json); assertThat(json).isEqualTo("{\"b\":{\"f\":\"test\"}}");
} }
/** /**
@ -92,7 +92,7 @@ public class TypeAdapterRuntimeTypeWrapperTest {
.create(); .create();
String json = gson.toJson(new Container()); String json = gson.toJson(new Container());
assertEquals("{\"b\":\"custom delegate\"}", json); assertThat(json).isEqualTo("{\"b\":\"custom delegate\"}");
} }
/** /**
@ -109,7 +109,7 @@ public class TypeAdapterRuntimeTypeWrapperTest {
.create(); .create();
String json = gson.toJson(new Container()); String json = gson.toJson(new Container());
assertEquals("{\"b\":{\"f\":\"test\"}}", json); assertThat(json).isEqualTo("{\"b\":{\"f\":\"test\"}}");
} }
/** /**
@ -131,7 +131,7 @@ public class TypeAdapterRuntimeTypeWrapperTest {
.create(); .create();
String json = gson.toJson(new Container()); String json = gson.toJson(new Container());
assertEquals("{\"b\":\"custom delegate\"}", json); assertThat(json).isEqualTo("{\"b\":\"custom delegate\"}");
} }
/** /**
@ -160,7 +160,7 @@ public class TypeAdapterRuntimeTypeWrapperTest {
.create(); .create();
String json = gson.toJson(new Container()); String json = gson.toJson(new Container());
assertEquals("{\"b\":{\"f\":\"test\"}}", json); assertThat(json).isEqualTo("{\"b\":{\"f\":\"test\"}}");
} }
private static class CyclicBase { private static class CyclicBase {
@ -188,6 +188,6 @@ public class TypeAdapterRuntimeTypeWrapperTest {
CyclicBase b = new CyclicBase(); CyclicBase b = new CyclicBase();
b.f = new CyclicSub(2); b.f = new CyclicSub(2);
String json = new Gson().toJson(b); String json = new Gson().toJson(b);
assertEquals("{\"f\":{\"i\":2}}", json); assertThat(json).isEqualTo("{\"f\":{\"i\":2}}");
} }
} }

View File

@ -16,7 +16,7 @@
package com.google.gson.functional; 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.Gson;
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;
@ -67,7 +67,7 @@ public final class TypeHierarchyAdapterTest {
company.ceo = eric; company.ceo = eric;
String json = gson.toJson(company, Company.class); String json = gson.toJson(company, Company.class);
assertEquals("{\n" + assertThat(json).isEqualTo("{\n" +
" \"ceo\": {\n" + " \"ceo\": {\n" +
" \"userid\": \"eric\",\n" + " \"userid\": \"eric\",\n" +
" \"startDate\": 2001,\n" + " \"startDate\": 2001,\n" +
@ -104,19 +104,17 @@ public final class TypeHierarchyAdapterTest {
" \"startDate\": 2006\n" + " \"startDate\": 2006\n" +
" }\n" + " }\n" +
" }\n" + " }\n" +
"}", json); "}");
Company copied = gson.fromJson(json, Company.class); Company copied = gson.fromJson(json, Company.class);
assertEquals(json, gson.toJson(copied, Company.class)); assertThat(gson.toJson(copied, Company.class)).isEqualTo(json);
assertEquals(copied.ceo.userid, company.ceo.userid); assertThat(company.ceo.userid).isEqualTo(copied.ceo.userid);
assertEquals(copied.ceo.assistant.userid, company.ceo.assistant.userid); assertThat(company.ceo.assistant.userid).isEqualTo(copied.ceo.assistant.userid);
assertEquals(copied.ceo.minions[0].userid, company.ceo.minions[0].userid); assertThat(company.ceo.minions[0].userid).isEqualTo(copied.ceo.minions[0].userid);
assertEquals(copied.ceo.minions[1].userid, company.ceo.minions[1].userid); assertThat(company.ceo.minions[1].userid).isEqualTo(copied.ceo.minions[1].userid);
assertEquals(copied.ceo.minions[2].userid, company.ceo.minions[2].userid); assertThat(company.ceo.minions[2].userid).isEqualTo(copied.ceo.minions[2].userid);
assertEquals(((Manager) copied.ceo.minions[2]).minions[0].userid, assertThat(((Manager) company.ceo.minions[2]).minions[0].userid).isEqualTo(((Manager) copied.ceo.minions[2]).minions[0].userid);
((Manager) company.ceo.minions[2]).minions[0].userid); assertThat(((Manager) company.ceo.minions[2]).minions[1].userid).isEqualTo(((Manager) copied.ceo.minions[2]).minions[1].userid);
assertEquals(((Manager) copied.ceo.minions[2]).minions[1].userid,
((Manager) company.ceo.minions[2]).minions[1].userid);
} }
@Test @Test
@ -130,9 +128,9 @@ public final class TypeHierarchyAdapterTest {
manager.userid = "inder"; manager.userid = "inder";
String json = gson.toJson(manager, Manager.class); String json = gson.toJson(manager, Manager.class);
assertEquals("\"inder\"", json); assertThat(json).isEqualTo("\"inder\"");
Manager copied = gson.fromJson(json, Manager.class); 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. */ /** This behaviour changed in Gson 2.1; it used to throw. */

View File

@ -15,7 +15,7 @@
*/ */
package com.google.gson.functional; 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.Gson;
import com.google.gson.reflect.TypeToken; import com.google.gson.reflect.TypeToken;
@ -36,7 +36,7 @@ import org.junit.Test;
public class TypeVariableTest { public class TypeVariableTest {
@Test @Test
public void testAdvancedTypeVariables() throws Exception { public void testAdvancedTypeVariables() {
Gson gson = new Gson(); Gson gson = new Gson();
Bar bar1 = new Bar("someString", 1, true); Bar bar1 = new Bar("someString", 1, true);
ArrayList<Integer> arrayList = new ArrayList<>(); ArrayList<Integer> arrayList = new ArrayList<>();
@ -48,29 +48,29 @@ public class TypeVariableTest {
String json = gson.toJson(bar1); String json = gson.toJson(bar1);
Bar bar2 = gson.fromJson(json, Bar.class); Bar bar2 = gson.fromJson(json, Bar.class);
assertEquals(bar1, bar2); assertThat(bar2).isEqualTo(bar1);
} }
@Test @Test
public void testTypeVariablesViaTypeParameter() throws Exception { public void testTypeVariablesViaTypeParameter() {
Gson gson = new Gson(); Gson gson = new Gson();
Foo<String, Integer> original = new Foo<>("e", 5, false); Foo<String, Integer> original = new Foo<>("e", 5, false);
original.map.put("f", Arrays.asList(6, 7)); original.map.put("f", Arrays.asList(6, 7));
Type type = new TypeToken<Foo<String, Integer>>() {}.getType(); Type type = new TypeToken<Foo<String, Integer>>() {}.getType();
String json = gson.toJson(original, type); String json = gson.toJson(original, type);
assertEquals("{\"someSField\":\"e\",\"someTField\":5,\"map\":{\"f\":[6,7]},\"redField\":false}", assertThat(json)
json); .isEqualTo("{\"someSField\":\"e\",\"someTField\":5,\"map\":{\"f\":[6,7]},\"redField\":false}");
assertEquals(original, gson.<Foo<String, Integer>>fromJson(json, type)); assertThat(gson.<Foo<String, Integer>>fromJson(json, type)).isEqualTo(original);
} }
@Test @Test
public void testBasicTypeVariables() throws Exception { public void testBasicTypeVariables() {
Gson gson = new Gson(); Gson gson = new Gson();
Blue blue1 = new Blue(true); Blue blue1 = new Blue(true);
String json = gson.toJson(blue1); String json = gson.toJson(blue1);
Blue blue2 = gson.fromJson(json, Blue.class); Blue blue2 = gson.fromJson(json, Blue.class);
assertEquals(blue1, blue2); assertThat(blue2).isEqualTo(blue1);
} }
@SuppressWarnings("overrides") // for missing hashCode() override @SuppressWarnings("overrides") // for missing hashCode() override

View File

@ -15,9 +15,7 @@
*/ */
package com.google.gson.functional; package com.google.gson.functional;
import static org.junit.Assert.assertEquals; import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import com.google.gson.Gson; import com.google.gson.Gson;
@ -64,18 +62,18 @@ public class UncategorizedTest {
} }
@Test @Test
public void testObjectEqualButNotSameSerialization() throws Exception { public void testObjectEqualButNotSameSerialization() {
ClassOverridingEquals objA = new ClassOverridingEquals(); ClassOverridingEquals objA = new ClassOverridingEquals();
ClassOverridingEquals objB = new ClassOverridingEquals(); ClassOverridingEquals objB = new ClassOverridingEquals();
objB.ref = objA; objB.ref = objA;
String json = gson.toJson(objB); String json = gson.toJson(objB);
assertEquals(objB.getExpectedJson(), json); assertThat(json).isEqualTo(objB.getExpectedJson());
} }
@Test @Test
public void testStaticFieldsAreNotSerialized() { public void testStaticFieldsAreNotSerialized() {
BagOfPrimitives target = new BagOfPrimitives(); BagOfPrimitives target = new BagOfPrimitives();
assertFalse(gson.toJson(target).contains("DEFAULT_VALUE")); assertThat(gson.toJson(target)).doesNotContain("DEFAULT_VALUE");
} }
@Test @Test
@ -83,7 +81,7 @@ public class UncategorizedTest {
BagOfPrimitives bag = new BagOfPrimitives(); BagOfPrimitives bag = new BagOfPrimitives();
String json = gson.toJson(bag); String json = gson.toJson(bag);
BagOfPrimitives deserialized = gson.fromJson(json, BagOfPrimitives.class); BagOfPrimitives deserialized = gson.fromJson(json, BagOfPrimitives.class);
assertEquals(bag, deserialized); assertThat(deserialized).isEqualTo(bag);
} }
/** /**
@ -96,13 +94,13 @@ public class UncategorizedTest {
Gson gson = new GsonBuilder().registerTypeAdapter(Base.class, new BaseTypeAdapter()).create(); Gson gson = new GsonBuilder().registerTypeAdapter(Base.class, new BaseTypeAdapter()).create();
String json = "{\"opType\":\"OP1\"}"; String json = "{\"opType\":\"OP1\"}";
Base base = gson.fromJson(json, Base.class); Base base = gson.fromJson(json, Base.class);
assertTrue(base instanceof Derived1); assertThat(base).isInstanceOf(Derived1.class);
assertEquals(OperationType.OP1, base.opType); assertThat(base.opType).isEqualTo(OperationType.OP1);
json = "{\"opType\":\"OP2\"}"; json = "{\"opType\":\"OP2\"}";
base = gson.fromJson(json, Base.class); base = gson.fromJson(json, Base.class);
assertTrue(base instanceof Derived2); assertThat(base).isInstanceOf(Derived2.class);
assertEquals(OperationType.OP2, base.opType); assertThat(base.opType).isEqualTo(OperationType.OP2);
} }
/** /**
@ -113,7 +111,7 @@ public class UncategorizedTest {
public void testTrailingWhitespace() throws Exception { public void testTrailingWhitespace() throws Exception {
List<Integer> integers = gson.fromJson("[1,2,3] \n\n ", List<Integer> integers = gson.fromJson("[1,2,3] \n\n ",
new TypeToken<List<Integer>>() {}.getType()); new TypeToken<List<Integer>>() {}.getType());
assertEquals(Arrays.asList(1, 2, 3), integers); assertThat(integers).containsExactly(1, 2, 3).inOrder();
} }
private enum OperationType { OP1, OP2 } private enum OperationType { OP1, OP2 }

View File

@ -15,10 +15,7 @@
*/ */
package com.google.gson.functional; package com.google.gson.functional;
import static org.junit.Assert.assertEquals; import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;
@ -48,15 +45,15 @@ public class VersioningTest {
Version1 target = new Version1(); Version1 target = new Version1();
Gson gson = gsonWithVersion(1.29); Gson gson = gsonWithVersion(1.29);
String json = gson.toJson(target); String json = gson.toJson(target);
assertTrue(json.contains("\"a\":" + A)); assertThat(json).contains("\"a\":" + A);
gson = gsonWithVersion(1.3); gson = gsonWithVersion(1.3);
json = gson.toJson(target); json = gson.toJson(target);
assertFalse(json.contains("\"a\":" + A)); assertThat(json).doesNotContain("\"a\":" + A);
gson = gsonWithVersion(1.31); gson = gsonWithVersion(1.31);
json = gson.toJson(target); json = gson.toJson(target);
assertFalse(json.contains("\"a\":" + A)); assertThat(json).doesNotContain("\"a\":" + A);
} }
@Test @Test
@ -65,15 +62,15 @@ public class VersioningTest {
Gson gson = gsonWithVersion(1.29); Gson gson = gsonWithVersion(1.29);
Version1 version1 = gson.fromJson(json, Version1.class); Version1 version1 = gson.fromJson(json, Version1.class);
assertEquals(3, version1.a); assertThat(version1.a).isEqualTo(3);
gson = gsonWithVersion(1.3); gson = gsonWithVersion(1.3);
version1 = gson.fromJson(json, Version1.class); version1 = gson.fromJson(json, Version1.class);
assertEquals(A, version1.a); assertThat(version1.a).isEqualTo(A);
gson = gsonWithVersion(1.31); gson = gsonWithVersion(1.31);
version1 = gson.fromJson(json, Version1.class); version1 = gson.fromJson(json, Version1.class);
assertEquals(A, version1.a); assertThat(version1.a).isEqualTo(A);
} }
@Test @Test
@ -81,7 +78,7 @@ public class VersioningTest {
Gson gson = gsonWithVersion(1.0); Gson gson = gsonWithVersion(1.0);
String json1 = gson.toJson(new Version1()); String json1 = gson.toJson(new Version1());
String json2 = gson.toJson(new Version1_1()); String json2 = gson.toJson(new Version1_1());
assertEquals(json1, json2); assertThat(json2).isEqualTo(json1);
} }
@Test @Test
@ -89,18 +86,18 @@ public class VersioningTest {
Gson gson = gsonWithVersion(1.0); Gson gson = gsonWithVersion(1.0);
String json = "{\"a\":3,\"b\":4,\"c\":5}"; String json = "{\"a\":3,\"b\":4,\"c\":5}";
Version1 version1 = gson.fromJson(json, Version1.class); Version1 version1 = gson.fromJson(json, Version1.class);
assertEquals(3, version1.a); assertThat(version1.a).isEqualTo(3);
assertEquals(4, version1.b); assertThat(version1.b).isEqualTo(4);
Version1_1 version1_1 = gson.fromJson(json, Version1_1.class); Version1_1 version1_1 = gson.fromJson(json, Version1_1.class);
assertEquals(3, version1_1.a); assertThat(version1_1.a).isEqualTo(3);
assertEquals(4, version1_1.b); assertThat(version1_1.b).isEqualTo(4);
assertEquals(C, version1_1.c); assertThat(version1_1.c).isEqualTo(C);
} }
@Test @Test
public void testIgnoreLaterVersionClassSerialization() { public void testIgnoreLaterVersionClassSerialization() {
Gson gson = gsonWithVersion(1.0); Gson gson = gsonWithVersion(1.0);
assertEquals("null", gson.toJson(new Version1_2())); assertThat(gson.toJson(new Version1_2())).isEqualTo("null");
} }
@Test @Test
@ -110,14 +107,14 @@ public class VersioningTest {
Version1_2 version1_2 = gson.fromJson(json, Version1_2.class); Version1_2 version1_2 = gson.fromJson(json, Version1_2.class);
// Since the class is versioned to be after 1.0, we expect null // Since the class is versioned to be after 1.0, we expect null
// This is the new behavior in Gson 2.0 // This is the new behavior in Gson 2.0
assertNull(version1_2); assertThat(version1_2).isNull();
} }
@Test @Test
public void testVersionedGsonWithUnversionedClassesSerialization() { public void testVersionedGsonWithUnversionedClassesSerialization() {
Gson gson = gsonWithVersion(1.0); Gson gson = gsonWithVersion(1.0);
BagOfPrimitives target = new BagOfPrimitives(10, 20, false, "stringValue"); BagOfPrimitives target = new BagOfPrimitives(10, 20, false, "stringValue");
assertEquals(target.getExpectedJson(), gson.toJson(target)); assertThat(gson.toJson(target)).isEqualTo(target.getExpectedJson());
} }
@Test @Test
@ -130,7 +127,7 @@ public class VersioningTest {
expected.intValue = 20; expected.intValue = 20;
expected.booleanValue = false; expected.booleanValue = false;
BagOfPrimitives actual = gson.fromJson(json, BagOfPrimitives.class); BagOfPrimitives actual = gson.fromJson(json, BagOfPrimitives.class);
assertEquals(expected, actual); assertThat(actual).isEqualTo(expected);
} }
@Test @Test
@ -138,19 +135,19 @@ public class VersioningTest {
Gson gson = gsonWithVersion(1.0); Gson gson = gsonWithVersion(1.0);
SinceUntilMixing target = new SinceUntilMixing(); SinceUntilMixing target = new SinceUntilMixing();
String json = gson.toJson(target); String json = gson.toJson(target);
assertFalse(json.contains("\"b\":" + B)); assertThat(json).doesNotContain("\"b\":" + B);
gson = gsonWithVersion(1.2); gson = gsonWithVersion(1.2);
json = gson.toJson(target); json = gson.toJson(target);
assertTrue(json.contains("\"b\":" + B)); assertThat(json).contains("\"b\":" + B);
gson = gsonWithVersion(1.3); gson = gsonWithVersion(1.3);
json = gson.toJson(target); json = gson.toJson(target);
assertFalse(json.contains("\"b\":" + B)); assertThat(json).doesNotContain("\"b\":" + B);
gson = gsonWithVersion(1.4); gson = gsonWithVersion(1.4);
json = gson.toJson(target); json = gson.toJson(target);
assertFalse(json.contains("\"b\":" + B)); assertThat(json).doesNotContain("\"b\":" + B);
} }
@Test @Test
@ -158,23 +155,23 @@ public class VersioningTest {
String json = "{\"a\":5,\"b\":6}"; String json = "{\"a\":5,\"b\":6}";
Gson gson = gsonWithVersion(1.0); Gson gson = gsonWithVersion(1.0);
SinceUntilMixing result = gson.fromJson(json, SinceUntilMixing.class); SinceUntilMixing result = gson.fromJson(json, SinceUntilMixing.class);
assertEquals(5, result.a); assertThat(result.a).isEqualTo(5);
assertEquals(B, result.b); assertThat(result.b).isEqualTo(B);
gson = gsonWithVersion(1.2); gson = gsonWithVersion(1.2);
result = gson.fromJson(json, SinceUntilMixing.class); result = gson.fromJson(json, SinceUntilMixing.class);
assertEquals(5, result.a); assertThat(result.a).isEqualTo(5);
assertEquals(6, result.b); assertThat(result.b).isEqualTo(6);
gson = gsonWithVersion(1.3); gson = gsonWithVersion(1.3);
result = gson.fromJson(json, SinceUntilMixing.class); result = gson.fromJson(json, SinceUntilMixing.class);
assertEquals(5, result.a); assertThat(result.a).isEqualTo(5);
assertEquals(B, result.b); assertThat(result.b).isEqualTo(B);
gson = gsonWithVersion(1.4); gson = gsonWithVersion(1.4);
result = gson.fromJson(json, SinceUntilMixing.class); result = gson.fromJson(json, SinceUntilMixing.class);
assertEquals(5, result.a); assertThat(result.a).isEqualTo(5);
assertEquals(B, result.b); assertThat(result.b).isEqualTo(B);
} }
private static class Version1 { private static class Version1 {

View File

@ -1,6 +1,6 @@
package com.google.gson.internal; 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 static org.junit.Assert.fail;
import com.google.gson.InstanceCreator; import com.google.gson.InstanceCreator;
@ -33,11 +33,9 @@ public class ConstructorConstructorTest {
constructor.construct(); constructor.construct();
fail("Expected exception"); fail("Expected exception");
} catch (RuntimeException exception) { } catch (RuntimeException exception) {
assertEquals( assertThat(exception).hasMessageThat().isEqualTo("Abstract classes can't be instantiated! "
"Abstract classes can't be instantiated! Register an InstanceCreator or a TypeAdapter for this " + "Register an InstanceCreator or a TypeAdapter for this type. "
+ "type. Class name: com.google.gson.internal.ConstructorConstructorTest$AbstractClass", + "Class name: com.google.gson.internal.ConstructorConstructorTest$AbstractClass");
exception.getMessage()
);
} }
} }
@ -48,11 +46,9 @@ public class ConstructorConstructorTest {
constructor.construct(); constructor.construct();
fail("Expected exception"); fail("Expected exception");
} catch (RuntimeException exception) { } catch (RuntimeException exception) {
assertEquals( assertThat(exception).hasMessageThat().isEqualTo("Interfaces can't be instantiated! "
"Interfaces can't be instantiated! Register an InstanceCreator or a TypeAdapter for " + "Register an InstanceCreator or a TypeAdapter for this type. "
+ "this type. Interface name: com.google.gson.internal.ConstructorConstructorTest$Interface", + "Interface name: com.google.gson.internal.ConstructorConstructorTest$Interface");
exception.getMessage()
);
} }
} }
} }

View File

@ -15,7 +15,7 @@
*/ */
package com.google.gson.internal; package com.google.gson.internal;
import static org.junit.Assert.assertFalse; import static com.google.common.truth.Truth.assertThat;
import org.junit.Test; import org.junit.Test;
@ -28,6 +28,6 @@ public class GsonBuildConfigTest {
@Test @Test
public void testEnsureGsonBuildConfigGetsUpdatedToMavenVersion() { public void testEnsureGsonBuildConfigGetsUpdatedToMavenVersion() {
assertFalse("${project.version}".equals(GsonBuildConfig.VERSION)); assertThat("${project.version}").isNotEqualTo(GsonBuildConfig.VERSION);
} }
} }

View File

@ -16,8 +16,7 @@
package com.google.gson.internal; package com.google.gson.internal;
import static org.junit.Assert.assertEquals; import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import java.lang.reflect.ParameterizedType; import java.lang.reflect.ParameterizedType;
@ -31,11 +30,11 @@ public final class GsonTypesTest {
public void testNewParameterizedTypeWithoutOwner() throws Exception { public void testNewParameterizedTypeWithoutOwner() throws Exception {
// List<A>. List is a top-level class // List<A>. List is a top-level class
Type type = $Gson$Types.newParameterizedTypeWithOwner(null, List.class, A.class); Type type = $Gson$Types.newParameterizedTypeWithOwner(null, List.class, A.class);
assertEquals(A.class, getFirstTypeArgument(type)); assertThat(getFirstTypeArgument(type)).isEqualTo(A.class);
// A<B>. A is a static inner class. // A<B>. A is a static inner class.
type = $Gson$Types.newParameterizedTypeWithOwner(null, A.class, B.class); type = $Gson$Types.newParameterizedTypeWithOwner(null, A.class, B.class);
assertEquals(B.class, getFirstTypeArgument(type)); assertThat(getFirstTypeArgument(type)).isEqualTo(B.class);
final class D { final class D {
} }
@ -47,15 +46,15 @@ public final class GsonTypesTest {
// A<D> is allowed. // A<D> is allowed.
type = $Gson$Types.newParameterizedTypeWithOwner(null, A.class, D.class); type = $Gson$Types.newParameterizedTypeWithOwner(null, A.class, D.class);
assertEquals(D.class, getFirstTypeArgument(type)); assertThat(getFirstTypeArgument(type)).isEqualTo(D.class);
} }
@Test @Test
public void testGetFirstTypeArgument() throws Exception { 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); 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 { private static final class A {

View File

@ -15,8 +15,7 @@
*/ */
package com.google.gson.internal; package com.google.gson.internal;
import static org.junit.Assert.assertEquals; import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertTrue;
import org.junit.Test; import org.junit.Test;
@ -30,51 +29,51 @@ public class JavaVersionTest {
@Test @Test
public void testGetMajorJavaVersion() { 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 @Test
public void testJava6() { 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 @Test
public void testJava7() { 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 @Test
public void testJava8() { public void testJava8() {
assertEquals(8, JavaVersion.getMajorJavaVersion("1.8")); assertThat(JavaVersion.getMajorJavaVersion("1.8")).isEqualTo(8);
assertEquals(8, JavaVersion.getMajorJavaVersion("1.8.0")); assertThat(JavaVersion.getMajorJavaVersion("1.8.0")).isEqualTo(8);
assertEquals(8, JavaVersion.getMajorJavaVersion("1.8.0_131")); assertThat(JavaVersion.getMajorJavaVersion("1.8.0_131")).isEqualTo(8);
assertEquals(8, JavaVersion.getMajorJavaVersion("1.8.0_60-ea")); assertThat(JavaVersion.getMajorJavaVersion("1.8.0_60-ea")).isEqualTo(8);
assertEquals(8, JavaVersion.getMajorJavaVersion("1.8.0_111-internal")); assertThat(JavaVersion.getMajorJavaVersion("1.8.0_111-internal")).isEqualTo(8);
// openjdk8 per https://github.com/AdoptOpenJDK/openjdk-build/issues/93 // openjdk8 per https://github.com/AdoptOpenJDK/openjdk-build/issues/93
assertEquals(8, JavaVersion.getMajorJavaVersion("1.8.0-internal")); assertThat(JavaVersion.getMajorJavaVersion("1.8.0-internal")).isEqualTo(8);
assertEquals(8, JavaVersion.getMajorJavaVersion("1.8.0_131-adoptopenjdk")); assertThat(JavaVersion.getMajorJavaVersion("1.8.0_131-adoptopenjdk")).isEqualTo(8);
} }
@Test @Test
public void testJava9() { public void testJava9() {
// Legacy style // Legacy style
assertEquals(9, JavaVersion.getMajorJavaVersion("9.0.4")); // Oracle JDK 9 assertThat(JavaVersion.getMajorJavaVersion("9.0.4")).isEqualTo(9); // Oracle JDK 9
assertEquals(9, JavaVersion.getMajorJavaVersion("9-Debian")); // Debian as reported in https://github.com/google/gson/issues/1310 assertThat(JavaVersion.getMajorJavaVersion("9-Debian")).isEqualTo(9); // Debian as reported in https://github.com/google/gson/issues/1310
// New style // New style
assertEquals(9, JavaVersion.getMajorJavaVersion("9-ea+19")); assertThat(JavaVersion.getMajorJavaVersion("9-ea+19")).isEqualTo(9);
assertEquals(9, JavaVersion.getMajorJavaVersion("9+100")); assertThat(JavaVersion.getMajorJavaVersion("9+100")).isEqualTo(9);
assertEquals(9, JavaVersion.getMajorJavaVersion("9.0.1+20")); assertThat(JavaVersion.getMajorJavaVersion("9.0.1+20")).isEqualTo(9);
assertEquals(9, JavaVersion.getMajorJavaVersion("9.1.1+20")); assertThat(JavaVersion.getMajorJavaVersion("9.1.1+20")).isEqualTo(9);
} }
@Test @Test
public void testJava10() { 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 @Test
public void testUnknownVersionFormat() { public void testUnknownVersionFormat() {
assertEquals(6, JavaVersion.getMajorJavaVersion("Java9")); // unknown format assertThat(JavaVersion.getMajorJavaVersion("Java9")).isEqualTo(6); // unknown format
} }
} }

View File

@ -15,8 +15,7 @@
*/ */
package com.google.gson.internal; package com.google.gson.internal;
import static org.junit.Assert.assertEquals; import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertTrue;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
@ -31,14 +30,14 @@ public class LazilyParsedNumberTest {
public void testHashCode() { public void testHashCode() {
LazilyParsedNumber n1 = new LazilyParsedNumber("1"); LazilyParsedNumber n1 = new LazilyParsedNumber("1");
LazilyParsedNumber n1Another = new LazilyParsedNumber("1"); LazilyParsedNumber n1Another = new LazilyParsedNumber("1");
assertEquals(n1.hashCode(), n1Another.hashCode()); assertThat(n1Another.hashCode()).isEqualTo(n1.hashCode());
} }
@Test @Test
public void testEquals() { public void testEquals() {
LazilyParsedNumber n1 = new LazilyParsedNumber("1"); LazilyParsedNumber n1 = new LazilyParsedNumber("1");
LazilyParsedNumber n1Another = new LazilyParsedNumber("1"); LazilyParsedNumber n1Another = new LazilyParsedNumber("1");
assertTrue(n1.equals(n1Another)); assertThat(n1.equals(n1Another)).isTrue();
} }
@Test @Test
@ -50,6 +49,6 @@ public class LazilyParsedNumberTest {
ObjectInputStream objIn = new ObjectInputStream(new ByteArrayInputStream(out.toByteArray())); ObjectInputStream objIn = new ObjectInputStream(new ByteArrayInputStream(out.toByteArray()));
Number deserialized = (Number) objIn.readObject(); Number deserialized = (Number) objIn.readObject();
assertEquals(new BigDecimal("123"), deserialized); assertThat(deserialized).isEqualTo(new BigDecimal("123"));
} }
} }

View File

@ -16,10 +16,7 @@
package com.google.gson.internal; package com.google.gson.internal;
import static org.junit.Assert.assertEquals; import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import com.google.gson.common.MoreAsserts; import com.google.gson.common.MoreAsserts;
@ -86,10 +83,11 @@ public final class LinkedTreeMapTest {
public void testPutNullValue() { public void testPutNullValue() {
LinkedTreeMap<String, String> map = new LinkedTreeMap<>(); LinkedTreeMap<String, String> map = new LinkedTreeMap<>();
map.put("a", null); map.put("a", null);
assertEquals(1, map.size());
assertTrue(map.containsKey("a")); assertThat(map).hasSize(1);
assertTrue(map.containsValue(null)); assertThat(map.containsKey("a")).isTrue();
assertNull(map.get("a")); assertThat(map.containsValue(null)).isTrue();
assertThat(map.get("a")).isNull();
} }
@Test @Test
@ -99,27 +97,27 @@ public final class LinkedTreeMapTest {
map.put("a", null); map.put("a", null);
fail(); fail();
} catch (NullPointerException e) { } catch (NullPointerException e) {
assertEquals("value == null", e.getMessage()); assertThat(e.getMessage()).isEqualTo("value == null");
} }
assertEquals(0, map.size()); assertThat(map).hasSize(0);
assertFalse(map.containsKey("a")); assertThat(map).doesNotContainKey("a");
assertFalse(map.containsValue(null)); assertThat(map.containsValue(null)).isFalse();
} }
@Test @Test
public void testEntrySetValueNull() { public void testEntrySetValueNull() {
LinkedTreeMap<String, String> map = new LinkedTreeMap<>(); LinkedTreeMap<String, String> map = new LinkedTreeMap<>();
map.put("a", "1"); map.put("a", "1");
assertEquals("1", map.get("a")); assertThat(map.get("a")).isEqualTo("1");
Entry<String, String> entry = map.entrySet().iterator().next(); Entry<String, String> entry = map.entrySet().iterator().next();
assertEquals("a", entry.getKey()); assertThat(entry.getKey()).isEqualTo("a");
assertEquals("1", entry.getValue()); assertThat(entry.getValue()).isEqualTo("1");
entry.setValue(null); entry.setValue(null);
assertNull(entry.getValue()); assertThat(entry.getValue()).isNull();
assertTrue(map.containsKey("a")); assertThat(map.containsKey("a")).isTrue();
assertTrue(map.containsValue(null)); assertThat(map.containsValue(null)).isTrue();
assertNull(map.get("a")); assertThat(map.get("a")).isNull();
} }
@ -132,47 +130,47 @@ public final class LinkedTreeMapTest {
entry.setValue(null); entry.setValue(null);
fail(); fail();
} catch (NullPointerException e) { } catch (NullPointerException e) {
assertEquals("value == null", e.getMessage()); assertThat(e.getMessage()).isEqualTo("value == null");
} }
assertEquals("1", entry.getValue()); assertThat(entry.getValue()).isEqualTo("1");
assertEquals("1", map.get("a")); assertThat(map.get("a")).isEqualTo("1");
assertFalse(map.containsValue(null)); assertThat(map.containsValue(null)).isFalse();
} }
@Test @Test
public void testContainsNonComparableKeyReturnsFalse() { public void testContainsNonComparableKeyReturnsFalse() {
LinkedTreeMap<String, String> map = new LinkedTreeMap<>(); LinkedTreeMap<String, String> map = new LinkedTreeMap<>();
map.put("a", "android"); map.put("a", "android");
assertFalse(map.containsKey(new Object())); assertThat(map).doesNotContainKey(new Object());
} }
@Test @Test
public void testContainsNullKeyIsAlwaysFalse() { public void testContainsNullKeyIsAlwaysFalse() {
LinkedTreeMap<String, String> map = new LinkedTreeMap<>(); LinkedTreeMap<String, String> map = new LinkedTreeMap<>();
assertFalse(map.containsKey(null)); assertThat(map.containsKey(null)).isFalse();
map.put("a", "android"); map.put("a", "android");
assertFalse(map.containsKey(null)); assertThat(map.containsKey(null)).isFalse();
} }
@Test @Test
public void testPutOverrides() throws Exception { public void testPutOverrides() throws Exception {
LinkedTreeMap<String, String> map = new LinkedTreeMap<>(); LinkedTreeMap<String, String> map = new LinkedTreeMap<>();
assertNull(map.put("d", "donut")); assertThat(map.put("d", "donut")).isNull();
assertNull(map.put("e", "eclair")); assertThat(map.put("e", "eclair")).isNull();
assertNull(map.put("f", "froyo")); assertThat(map.put("f", "froyo")).isNull();
assertEquals(3, map.size()); assertThat(map).hasSize(3);
assertEquals("donut", map.get("d")); assertThat(map.get("d")).isEqualTo("donut");
assertEquals("donut", map.put("d", "done")); assertThat(map.put("d", "done")).isEqualTo("donut");
assertEquals(3, map.size()); assertThat(map).hasSize(3);
} }
@Test @Test
public void testEmptyStringValues() { public void testEmptyStringValues() {
LinkedTreeMap<String, String> map = new LinkedTreeMap<>(); LinkedTreeMap<String, String> map = new LinkedTreeMap<>();
map.put("a", ""); map.put("a", "");
assertTrue(map.containsKey("a")); assertThat(map.containsKey("a")).isTrue();
assertEquals("", map.get("a")); assertThat(map.get("a")).isEqualTo("");
} }
@Test @Test
@ -187,8 +185,8 @@ public final class LinkedTreeMapTest {
for (int i = 0; i < keys.length; i++) { for (int i = 0; i < keys.length; i++) {
String key = keys[i]; String key = keys[i];
assertTrue(map.containsKey(key)); assertThat(map.containsKey(key)).isTrue();
assertEquals("" + i, map.get(key)); assertThat(map.get(key)).isEqualTo("" + i);
} }
} }
@ -200,7 +198,7 @@ public final class LinkedTreeMapTest {
map.put("b", "bbq"); map.put("b", "bbq");
map.clear(); map.clear();
assertIterationOrder(map.keySet()); assertIterationOrder(map.keySet());
assertEquals(0, map.size()); assertThat(map).hasSize(0);
} }
@Test @Test
@ -232,7 +230,7 @@ public final class LinkedTreeMapTest {
ObjectInputStream objIn = new ObjectInputStream(new ByteArrayInputStream(out.toByteArray())); ObjectInputStream objIn = new ObjectInputStream(new ByteArrayInputStream(out.toByteArray()));
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
Map<String, Integer> deserialized = (Map<String, Integer>) objIn.readObject(); Map<String, Integer> deserialized = (Map<String, Integer>) objIn.readObject();
assertEquals(Collections.singletonMap("a", 1), deserialized); assertThat(deserialized).isEqualTo(Collections.singletonMap("a", 1));
} }
@SuppressWarnings("varargs") @SuppressWarnings("varargs")
@ -242,6 +240,6 @@ public final class LinkedTreeMapTest {
for (T t : actual) { for (T t : actual) {
actualList.add(t); actualList.add(t);
} }
assertEquals(Arrays.asList(expected), actualList); assertThat(actualList).isEqualTo(Arrays.asList(expected));
} }
} }

View File

@ -1,6 +1,6 @@
package com.google.gson.internal; 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 static org.junit.Assert.fail;
import java.io.IOException; import java.io.IOException;
@ -57,12 +57,12 @@ public class StreamsTest {
} }
String actualOutput = stringBuilder.toString(); 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.flush();
writer.close(); writer.close();
// flush() and close() calls should have had no effect // flush() and close() calls should have had no effect
assertEquals(actualOutput, stringBuilder.toString()); assertThat(stringBuilder.toString()).isEqualTo(actualOutput);
} }
} }

View File

@ -15,8 +15,7 @@
*/ */
package com.google.gson.internal; package com.google.gson.internal;
import static org.junit.Assert.assertNotNull; import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import org.junit.Test; import org.junit.Test;
@ -46,7 +45,7 @@ public final class UnsafeAllocatorInstantiationTest {
UnsafeAllocator.INSTANCE.newInstance(Interface.class); UnsafeAllocator.INSTANCE.newInstance(Interface.class);
fail(); fail();
} catch (AssertionError e) { } 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 final class UnsafeAllocatorInstantiationTest {
UnsafeAllocator.INSTANCE.newInstance(AbstractClass.class); UnsafeAllocator.INSTANCE.newInstance(AbstractClass.class);
fail(); fail();
} catch (AssertionError e) { } 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 final class UnsafeAllocatorInstantiationTest {
@Test @Test
public void testConcreteClassInstantiation() throws Exception { public void testConcreteClassInstantiation() throws Exception {
ConcreteClass instance = UnsafeAllocator.INSTANCE.newInstance(ConcreteClass.class); ConcreteClass instance = UnsafeAllocator.INSTANCE.newInstance(ConcreteClass.class);
assertNotNull(instance); assertThat(instance).isNotNull();
} }
} }

View File

@ -16,9 +16,8 @@
package com.google.gson.internal.bind; 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.assertNotNull; import static com.google.common.truth.Truth.assertWithMessage;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import com.google.gson.Gson; import com.google.gson.Gson;
@ -171,29 +170,29 @@ public class DefaultDateTypeAdapterTest {
} }
@Test @Test
public void testDateSerialization() throws Exception { public void testDateSerialization() {
int dateStyle = DateFormat.LONG; int dateStyle = DateFormat.LONG;
TypeAdapter<Date> dateTypeAdapter = dateAdapter(DateType.DATE.createAdapterFactory(dateStyle)); TypeAdapter<Date> dateTypeAdapter = dateAdapter(DateType.DATE.createAdapterFactory(dateStyle));
DateFormat formatter = DateFormat.getDateInstance(dateStyle, Locale.US); DateFormat formatter = DateFormat.getDateInstance(dateStyle, Locale.US);
Date currentDate = new Date(); Date currentDate = new Date();
String dateString = dateTypeAdapter.toJson(currentDate); String dateString = dateTypeAdapter.toJson(currentDate);
assertEquals(toLiteral(formatter.format(currentDate)), dateString); assertThat(dateString).isEqualTo(toLiteral(formatter.format(currentDate)));
} }
@Test @Test
public void testDatePattern() throws Exception { public void testDatePattern() {
String pattern = "yyyy-MM-dd"; String pattern = "yyyy-MM-dd";
TypeAdapter<Date> dateTypeAdapter = dateAdapter(DateType.DATE.createAdapterFactory(pattern)); TypeAdapter<Date> dateTypeAdapter = dateAdapter(DateType.DATE.createAdapterFactory(pattern));
DateFormat formatter = new SimpleDateFormat(pattern); DateFormat formatter = new SimpleDateFormat(pattern);
Date currentDate = new Date(); Date currentDate = new Date();
String dateString = dateTypeAdapter.toJson(currentDate); String dateString = dateTypeAdapter.toJson(currentDate);
assertEquals(toLiteral(formatter.format(currentDate)), dateString); assertThat(dateString).isEqualTo(toLiteral(formatter.format(currentDate)));
} }
@Test @Test
public void testInvalidDatePattern() throws Exception { public void testInvalidDatePattern() {
try { try {
DateType.DATE.createAdapterFactory("I am a bad Date pattern...."); DateType.DATE.createAdapterFactory("I am a bad Date pattern....");
fail("Invalid date pattern should fail."); fail("Invalid date pattern should fail.");
@ -203,8 +202,8 @@ public class DefaultDateTypeAdapterTest {
@Test @Test
public void testNullValue() throws Exception { public void testNullValue() throws Exception {
TypeAdapter<Date> adapter = dateAdapter(DateType.DATE.createDefaultsAdapterFactory()); TypeAdapter<Date> adapter = dateAdapter(DateType.DATE.createDefaultsAdapterFactory());
assertNull(adapter.fromJson("null")); assertThat(adapter.fromJson("null")).isNull();
assertEquals("null", adapter.toJson(null)); assertThat(adapter.toJson(null)).isEqualTo("null");
} }
@Test @Test
@ -218,19 +217,19 @@ public class DefaultDateTypeAdapterTest {
private static TypeAdapter<Date> dateAdapter(TypeAdapterFactory adapterFactory) { private static TypeAdapter<Date> dateAdapter(TypeAdapterFactory adapterFactory) {
TypeAdapter<Date> adapter = adapterFactory.create(new Gson(), TypeToken.get(Date.class)); TypeAdapter<Date> adapter = adapterFactory.create(new Gson(), TypeToken.get(Date.class));
assertNotNull(adapter); assertThat(adapter).isNotNull();
return adapter; return adapter;
} }
private static void assertFormatted(String formatted, TypeAdapterFactory adapterFactory) { private static void assertFormatted(String formatted, TypeAdapterFactory adapterFactory) {
TypeAdapter<Date> adapter = dateAdapter(adapterFactory); TypeAdapter<Date> 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 { private static void assertParsed(String date, TypeAdapterFactory adapterFactory) throws IOException {
TypeAdapter<Date> adapter = dateAdapter(adapterFactory); TypeAdapter<Date> adapter = dateAdapter(adapterFactory);
assertEquals(date, new Date(0), adapter.fromJson(toLiteral(date))); assertWithMessage(date).that(adapter.fromJson(toLiteral(date))).isEqualTo(new Date(0));
assertEquals("ISO 8601", new Date(0), adapter.fromJson(toLiteral("1970-01-01T00:00:00Z"))); assertWithMessage("ISO 8601").that(adapter.fromJson(toLiteral("1970-01-01T00:00:00Z"))).isEqualTo(new Date(0));
} }
private static String toLiteral(String s) { private static String toLiteral(String s) {

View File

@ -1,7 +1,6 @@
package com.google.gson.internal.bind; 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.assertNotEquals;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;
@ -39,7 +38,7 @@ public class Java17ReflectiveTypeAdapterFactoryTest {
Gson gson = new Gson(); Gson gson = new Gson();
TypeAdapter<?> recordAdapter = gson.getAdapter(unixDomainPrincipalClass); TypeAdapter<?> recordAdapter = gson.getAdapter(unixDomainPrincipalClass);
TypeAdapter<?> defaultReflectionAdapter = gson.getAdapter(DummyClass.class); TypeAdapter<?> defaultReflectionAdapter = gson.getAdapter(DummyClass.class);
assertNotEquals(recordAdapter.getClass(), defaultReflectionAdapter.getClass()); assertThat(defaultReflectionAdapter.getClass()).isNotEqualTo(recordAdapter.getClass());
} }
@Test @Test
@ -59,8 +58,8 @@ public class Java17ReflectiveTypeAdapterFactoryTest {
String serialized = gson.toJson(recordInstance); String serialized = gson.toJson(recordInstance);
Object deserializedRecordInstance = gson.fromJson(serialized, unixDomainPrincipalClass); Object deserializedRecordInstance = gson.fromJson(serialized, unixDomainPrincipalClass);
assertEquals(recordInstance, deserializedRecordInstance); assertThat(deserializedRecordInstance).isEqualTo(recordInstance);
assertEquals("{\"user\":\"user\",\"group\":\"group\"}", serialized); assertThat(serialized).isEqualTo("{\"user\":\"user\",\"group\":\"group\"}");
} }
private static class PrincipalTypeAdapter<T extends Principal> extends TypeAdapter<T> { private static class PrincipalTypeAdapter<T extends Principal> extends TypeAdapter<T> {

View File

@ -16,8 +16,7 @@
package com.google.gson.internal.bind; 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.assertTrue;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import com.google.gson.JsonElement; import com.google.gson.JsonElement;
@ -36,9 +35,9 @@ public final class JsonElementReaderTest {
JsonElement element = JsonParser.parseString("[1, 2, 3]"); JsonElement element = JsonParser.parseString("[1, 2, 3]");
JsonTreeReader reader = new JsonTreeReader(element); JsonTreeReader reader = new JsonTreeReader(element);
reader.beginArray(); reader.beginArray();
assertEquals(1, reader.nextInt()); assertThat(reader.nextInt()).isEqualTo(1);
assertEquals(2L, reader.nextLong()); assertThat(reader.nextLong()).isEqualTo(2L);
assertEquals(3.0, reader.nextDouble(), 0); assertThat(reader.nextDouble()).isEqualTo(3.0);
reader.endArray(); reader.endArray();
} }
@ -48,9 +47,9 @@ public final class JsonElementReaderTest {
JsonTreeReader reader = new JsonTreeReader(element); JsonTreeReader reader = new JsonTreeReader(element);
reader.setLenient(true); reader.setLenient(true);
reader.beginArray(); reader.beginArray();
assertTrue(Double.isNaN(reader.nextDouble())); assertThat(Double.isNaN(reader.nextDouble())).isTrue();
assertEquals(Double.NEGATIVE_INFINITY, reader.nextDouble(), 0); assertThat(reader.nextDouble()).isEqualTo(Double.NEGATIVE_INFINITY);
assertEquals(Double.POSITIVE_INFINITY, reader.nextDouble(), 0); assertThat(reader.nextDouble()).isEqualTo(Double.POSITIVE_INFINITY);
reader.endArray(); reader.endArray();
} }
@ -64,23 +63,23 @@ public final class JsonElementReaderTest {
reader.nextDouble(); reader.nextDouble();
fail(); fail();
} catch (MalformedJsonException e) { } 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 { try {
reader.nextDouble(); reader.nextDouble();
fail(); fail();
} catch (MalformedJsonException e) { } 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 { try {
reader.nextDouble(); reader.nextDouble();
fail(); fail();
} catch (MalformedJsonException e) { } 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(); reader.endArray();
} }
@ -89,9 +88,9 @@ public final class JsonElementReaderTest {
JsonElement element = JsonParser.parseString("[\"1\", \"2\", \"3\"]"); JsonElement element = JsonParser.parseString("[\"1\", \"2\", \"3\"]");
JsonTreeReader reader = new JsonTreeReader(element); JsonTreeReader reader = new JsonTreeReader(element);
reader.beginArray(); reader.beginArray();
assertEquals(1, reader.nextInt()); assertThat(reader.nextInt()).isEqualTo(1);
assertEquals(2L, reader.nextLong()); assertThat(reader.nextLong()).isEqualTo(2L);
assertEquals(3.0, reader.nextDouble(), 0); assertThat(reader.nextDouble()).isEqualTo(3.0);
reader.endArray(); reader.endArray();
} }
@ -100,7 +99,7 @@ public final class JsonElementReaderTest {
JsonElement element = JsonParser.parseString("[1]"); JsonElement element = JsonParser.parseString("[1]");
JsonTreeReader reader = new JsonTreeReader(element); JsonTreeReader reader = new JsonTreeReader(element);
reader.beginArray(); reader.beginArray();
assertEquals("1", reader.nextString()); assertThat(reader.nextString()).isEqualTo("1");
reader.endArray(); reader.endArray();
} }
@ -109,8 +108,8 @@ public final class JsonElementReaderTest {
JsonElement element = JsonParser.parseString("[true, false]"); JsonElement element = JsonParser.parseString("[true, false]");
JsonTreeReader reader = new JsonTreeReader(element); JsonTreeReader reader = new JsonTreeReader(element);
reader.beginArray(); reader.beginArray();
assertEquals(true, reader.nextBoolean()); assertThat(reader.nextBoolean()).isEqualTo(true);
assertEquals(false, reader.nextBoolean()); assertThat(reader.nextBoolean()).isEqualTo(false);
reader.endArray(); reader.endArray();
} }
@ -129,8 +128,8 @@ public final class JsonElementReaderTest {
JsonElement element = JsonParser.parseString("[\"A\",\"B\"]"); JsonElement element = JsonParser.parseString("[\"A\",\"B\"]");
JsonTreeReader reader = new JsonTreeReader(element); JsonTreeReader reader = new JsonTreeReader(element);
reader.beginArray(); reader.beginArray();
assertEquals("A", reader.nextString()); assertThat(reader.nextString()).isEqualTo("A");
assertEquals("B", reader.nextString()); assertThat(reader.nextString()).isEqualTo("B");
reader.endArray(); reader.endArray();
} }
@ -138,36 +137,36 @@ public final class JsonElementReaderTest {
public void testArray() throws IOException { public void testArray() throws IOException {
JsonElement element = JsonParser.parseString("[1, 2, 3]"); JsonElement element = JsonParser.parseString("[1, 2, 3]");
JsonTreeReader reader = new JsonTreeReader(element); JsonTreeReader reader = new JsonTreeReader(element);
assertEquals(JsonToken.BEGIN_ARRAY, reader.peek()); assertThat(reader.peek()).isEqualTo(JsonToken.BEGIN_ARRAY);
reader.beginArray(); reader.beginArray();
assertEquals(JsonToken.NUMBER, reader.peek()); assertThat(reader.peek()).isEqualTo(JsonToken.NUMBER);
assertEquals(1, reader.nextInt()); assertThat(reader.nextInt()).isEqualTo(1);
assertEquals(JsonToken.NUMBER, reader.peek()); assertThat(reader.peek()).isEqualTo(JsonToken.NUMBER);
assertEquals(2, reader.nextInt()); assertThat(reader.nextInt()).isEqualTo(2);
assertEquals(JsonToken.NUMBER, reader.peek()); assertThat(reader.peek()).isEqualTo(JsonToken.NUMBER);
assertEquals(3, reader.nextInt()); assertThat(reader.nextInt()).isEqualTo(3);
assertEquals(JsonToken.END_ARRAY, reader.peek()); assertThat(reader.peek()).isEqualTo(JsonToken.END_ARRAY);
reader.endArray(); reader.endArray();
assertEquals(JsonToken.END_DOCUMENT, reader.peek()); assertThat(reader.peek()).isEqualTo(JsonToken.END_DOCUMENT);
} }
@Test @Test
public void testObject() throws IOException { public void testObject() throws IOException {
JsonElement element = JsonParser.parseString("{\"A\": 1, \"B\": 2}"); JsonElement element = JsonParser.parseString("{\"A\": 1, \"B\": 2}");
JsonTreeReader reader = new JsonTreeReader(element); JsonTreeReader reader = new JsonTreeReader(element);
assertEquals(JsonToken.BEGIN_OBJECT, reader.peek()); assertThat(reader.peek()).isEqualTo(JsonToken.BEGIN_OBJECT);
reader.beginObject(); reader.beginObject();
assertEquals(JsonToken.NAME, reader.peek()); assertThat(reader.peek()).isEqualTo(JsonToken.NAME);
assertEquals("A", reader.nextName()); assertThat(reader.nextName()).isEqualTo("A");
assertEquals(JsonToken.NUMBER, reader.peek()); assertThat(reader.peek()).isEqualTo(JsonToken.NUMBER);
assertEquals(1, reader.nextInt()); assertThat(reader.nextInt()).isEqualTo(1);
assertEquals(JsonToken.NAME, reader.peek()); assertThat(reader.peek()).isEqualTo(JsonToken.NAME);
assertEquals("B", reader.nextName()); assertThat(reader.nextName()).isEqualTo("B");
assertEquals(JsonToken.NUMBER, reader.peek()); assertThat(reader.peek()).isEqualTo(JsonToken.NUMBER);
assertEquals(2, reader.nextInt()); assertThat(reader.nextInt()).isEqualTo(2);
assertEquals(JsonToken.END_OBJECT, reader.peek()); assertThat(reader.peek()).isEqualTo(JsonToken.END_OBJECT);
reader.endObject(); reader.endObject();
assertEquals(JsonToken.END_DOCUMENT, reader.peek()); assertThat(reader.peek()).isEqualTo(JsonToken.END_DOCUMENT);
} }
@Test @Test
@ -197,12 +196,12 @@ public final class JsonElementReaderTest {
JsonElement element = JsonParser.parseString("{\"A\":{},\"B\":{\"C\":{}}}"); JsonElement element = JsonParser.parseString("{\"A\":{},\"B\":{\"C\":{}}}");
JsonTreeReader reader = new JsonTreeReader(element); JsonTreeReader reader = new JsonTreeReader(element);
reader.beginObject(); reader.beginObject();
assertEquals("A", reader.nextName()); assertThat(reader.nextName()).isEqualTo("A");
reader.beginObject(); reader.beginObject();
reader.endObject(); reader.endObject();
assertEquals("B", reader.nextName()); assertThat(reader.nextName()).isEqualTo("B");
reader.beginObject(); reader.beginObject();
assertEquals("C", reader.nextName()); assertThat(reader.nextName()).isEqualTo("C");
reader.beginObject(); reader.beginObject();
reader.endObject(); reader.endObject();
reader.endObject(); reader.endObject();
@ -222,11 +221,11 @@ public final class JsonElementReaderTest {
JsonElement element = JsonParser.parseString("[\"A\",{\"B\":[[]]},\"C\",[[]],\"D\",null]"); JsonElement element = JsonParser.parseString("[\"A\",{\"B\":[[]]},\"C\",[[]],\"D\",null]");
JsonTreeReader reader = new JsonTreeReader(element); JsonTreeReader reader = new JsonTreeReader(element);
reader.beginArray(); reader.beginArray();
assertEquals("A", reader.nextString()); assertThat(reader.nextString()).isEqualTo("A");
reader.skipValue(); reader.skipValue();
assertEquals("C", reader.nextString()); assertThat(reader.nextString()).isEqualTo("C");
reader.skipValue(); reader.skipValue();
assertEquals("D", reader.nextString()); assertThat(reader.nextString()).isEqualTo("D");
reader.skipValue(); reader.skipValue();
reader.endArray(); reader.endArray();
} }
@ -319,7 +318,7 @@ public final class JsonElementReaderTest {
fail(); fail();
} catch (IllegalStateException expected) { } catch (IllegalStateException expected) {
} }
assertEquals("A", reader.nextString()); assertThat(reader.nextString()).isEqualTo("A");
reader.endArray(); reader.endArray();
} }
@ -334,7 +333,7 @@ public final class JsonElementReaderTest {
} catch (IllegalStateException expected) { } catch (IllegalStateException expected) {
} }
reader.nextName(); reader.nextName();
assertEquals(reader.nextJsonElement(), new JsonPrimitive(1)); assertThat(new JsonPrimitive(1)).isEqualTo(reader.nextJsonElement());
reader.nextName(); reader.nextName();
reader.beginObject(); reader.beginObject();
try { try {

View File

@ -15,8 +15,7 @@
*/ */
package com.google.gson.internal.bind; 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.assertFalse;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import com.google.gson.JsonArray; import com.google.gson.JsonArray;
@ -39,8 +38,8 @@ public class JsonTreeReaderTest {
public void testSkipValue_emptyJsonObject() throws IOException { public void testSkipValue_emptyJsonObject() throws IOException {
JsonTreeReader in = new JsonTreeReader(new JsonObject()); JsonTreeReader in = new JsonTreeReader(new JsonObject());
in.skipValue(); in.skipValue();
assertEquals(JsonToken.END_DOCUMENT, in.peek()); assertThat(in.peek()).isEqualTo(JsonToken.END_DOCUMENT);
assertEquals("$", in.getPath()); assertThat(in.getPath()).isEqualTo("$");
} }
@Test @Test
@ -59,8 +58,8 @@ public class JsonTreeReaderTest {
jsonObject.addProperty("s", "text"); jsonObject.addProperty("s", "text");
JsonTreeReader in = new JsonTreeReader(jsonObject); JsonTreeReader in = new JsonTreeReader(jsonObject);
in.skipValue(); in.skipValue();
assertEquals(JsonToken.END_DOCUMENT, in.peek()); assertThat(in.peek()).isEqualTo(JsonToken.END_DOCUMENT);
assertEquals("$", in.getPath()); assertThat(in.getPath()).isEqualTo("$");
} }
@Test @Test
@ -70,9 +69,9 @@ public class JsonTreeReaderTest {
JsonTreeReader in = new JsonTreeReader(jsonObject); JsonTreeReader in = new JsonTreeReader(jsonObject);
in.beginObject(); in.beginObject();
in.skipValue(); in.skipValue();
assertEquals(JsonToken.STRING, in.peek()); assertThat(in.peek()).isEqualTo(JsonToken.STRING);
assertEquals("$.<skipped>", in.getPath()); assertThat(in.getPath()).isEqualTo("$.<skipped>");
assertEquals("value", in.nextString()); assertThat(in.nextString()).isEqualTo("value");
} }
@Test @Test
@ -80,12 +79,12 @@ public class JsonTreeReaderTest {
JsonTreeReader reader = new JsonTreeReader(new JsonObject()); JsonTreeReader reader = new JsonTreeReader(new JsonObject());
reader.beginObject(); reader.beginObject();
reader.endObject(); reader.endObject();
assertEquals(JsonToken.END_DOCUMENT, reader.peek()); assertThat(reader.peek()).isEqualTo(JsonToken.END_DOCUMENT);
assertEquals("$", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$");
reader.skipValue(); reader.skipValue();
assertEquals(JsonToken.END_DOCUMENT, reader.peek()); assertThat(reader.peek()).isEqualTo(JsonToken.END_DOCUMENT);
assertEquals("$", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$");
} }
@Test @Test
@ -93,8 +92,8 @@ public class JsonTreeReaderTest {
JsonTreeReader reader = new JsonTreeReader(new JsonArray()); JsonTreeReader reader = new JsonTreeReader(new JsonArray());
reader.beginArray(); reader.beginArray();
reader.skipValue(); reader.skipValue();
assertEquals(JsonToken.END_DOCUMENT, reader.peek()); assertThat(reader.peek()).isEqualTo(JsonToken.END_DOCUMENT);
assertEquals("$", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$");
} }
@Test @Test
@ -102,8 +101,8 @@ public class JsonTreeReaderTest {
JsonTreeReader reader = new JsonTreeReader(new JsonObject()); JsonTreeReader reader = new JsonTreeReader(new JsonObject());
reader.beginObject(); reader.beginObject();
reader.skipValue(); reader.skipValue();
assertEquals(JsonToken.END_DOCUMENT, reader.peek()); assertThat(reader.peek()).isEqualTo(JsonToken.END_DOCUMENT);
assertEquals("$", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$");
} }
@Test @Test
@ -111,7 +110,7 @@ public class JsonTreeReaderTest {
JsonTreeReader reader = new JsonTreeReader(new JsonObject()); JsonTreeReader reader = new JsonTreeReader(new JsonObject());
reader.beginObject(); reader.beginObject();
reader.endObject(); reader.endObject();
assertFalse(reader.hasNext()); assertThat(reader.hasNext()).isFalse();
} }
@Test @Test
@ -134,8 +133,7 @@ public class JsonTreeReaderTest {
reader.peek(); reader.peek();
fail(); fail();
} catch (MalformedJsonException expected) { } catch (MalformedJsonException expected) {
assertEquals("Custom JsonElement subclass " + CustomSubclass.class.getName() + " is not supported", assertThat(expected.getMessage()).isEqualTo("Custom JsonElement subclass " + CustomSubclass.class.getName() + " is not supported");
expected.getMessage());
} }
} }

View File

@ -16,7 +16,7 @@
package com.google.gson.internal.bind; 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 static org.junit.Assert.fail;
import com.google.gson.JsonElement; import com.google.gson.JsonElement;
@ -39,7 +39,7 @@ public final class JsonTreeWriterTest {
writer.value(2); writer.value(2);
writer.value(3); writer.value(3);
writer.endArray(); writer.endArray();
assertEquals("[1,2,3]", writer.get().toString()); assertThat(writer.get().toString()).isEqualTo("[1,2,3]");
} }
@Test @Test
@ -53,7 +53,7 @@ public final class JsonTreeWriterTest {
writer.endArray(); writer.endArray();
writer.endArray(); writer.endArray();
writer.endArray(); writer.endArray();
assertEquals("[[],[[]]]", writer.get().toString()); assertThat(writer.get().toString()).isEqualTo("[[],[[]]]");
} }
@Test @Test
@ -63,7 +63,7 @@ public final class JsonTreeWriterTest {
writer.name("A").value(1); writer.name("A").value(1);
writer.name("B").value(2); writer.name("B").value(2);
writer.endObject(); writer.endObject();
assertEquals("{\"A\":1,\"B\":2}", writer.get().toString()); assertThat(writer.get().toString()).isEqualTo("{\"A\":1,\"B\":2}");
} }
@Test @Test
@ -80,7 +80,7 @@ public final class JsonTreeWriterTest {
writer.beginObject(); writer.beginObject();
writer.endObject(); writer.endObject();
writer.endObject(); writer.endObject();
assertEquals("{\"A\":{\"B\":{}},\"C\":{}}", writer.get().toString()); assertThat(writer.get().toString()).isEqualTo("{\"A\":{\"B\":{}},\"C\":{}}");
} }
@Test @Test
@ -118,7 +118,7 @@ public final class JsonTreeWriterTest {
writer.name("A"); writer.name("A");
writer.nullValue(); writer.nullValue();
writer.endObject(); writer.endObject();
assertEquals("{}", writer.get().toString()); assertThat(writer.get().toString()).isEqualTo("{}");
} }
@Test @Test
@ -129,46 +129,46 @@ public final class JsonTreeWriterTest {
writer.name("A"); writer.name("A");
writer.nullValue(); writer.nullValue();
writer.endObject(); writer.endObject();
assertEquals("{\"A\":null}", writer.get().toString()); assertThat(writer.get().toString()).isEqualTo("{\"A\":null}");
} }
@Test @Test
public void testEmptyWriter() { public void testEmptyWriter() {
JsonTreeWriter writer = new JsonTreeWriter(); JsonTreeWriter writer = new JsonTreeWriter();
assertEquals(JsonNull.INSTANCE, writer.get()); assertThat(writer.get()).isEqualTo(JsonNull.INSTANCE);
} }
@Test @Test
public void testBeginArray() throws Exception { public void testBeginArray() throws Exception {
JsonTreeWriter writer = new JsonTreeWriter(); JsonTreeWriter writer = new JsonTreeWriter();
assertEquals(writer, writer.beginArray()); assertThat(writer.beginArray()).isEqualTo(writer);
} }
@Test @Test
public void testBeginObject() throws Exception { public void testBeginObject() throws Exception {
JsonTreeWriter writer = new JsonTreeWriter(); JsonTreeWriter writer = new JsonTreeWriter();
assertEquals(writer, writer.beginObject()); assertThat(writer.beginObject()).isEqualTo(writer);
} }
@Test @Test
public void testValueString() throws Exception { public void testValueString() throws Exception {
JsonTreeWriter writer = new JsonTreeWriter(); JsonTreeWriter writer = new JsonTreeWriter();
String n = "as"; String n = "as";
assertEquals(writer, writer.value(n)); assertThat(writer.value(n)).isEqualTo(writer);
} }
@Test @Test
public void testBoolValue() throws Exception { public void testBoolValue() throws Exception {
JsonTreeWriter writer = new JsonTreeWriter(); JsonTreeWriter writer = new JsonTreeWriter();
boolean bool = true; boolean bool = true;
assertEquals(writer, writer.value(bool)); assertThat(writer.value(bool)).isEqualTo(writer);
} }
@Test @Test
public void testBoolMaisValue() throws Exception { public void testBoolMaisValue() throws Exception {
JsonTreeWriter writer = new JsonTreeWriter(); JsonTreeWriter writer = new JsonTreeWriter();
Boolean bool = true; Boolean bool = true;
assertEquals(writer, writer.value(bool)); assertThat(writer.value(bool)).isEqualTo(writer);
} }
@Test @Test
@ -183,7 +183,7 @@ public final class JsonTreeWriterTest {
writer.value(Double.NEGATIVE_INFINITY); writer.value(Double.NEGATIVE_INFINITY);
writer.value(Double.POSITIVE_INFINITY); writer.value(Double.POSITIVE_INFINITY);
writer.endArray(); writer.endArray();
assertEquals("[NaN,-Infinity,Infinity,NaN,-Infinity,Infinity]", writer.get().toString()); assertThat(writer.get().toString()).isEqualTo("[NaN,-Infinity,Infinity,NaN,-Infinity,Infinity]");
} }
@Test @Test

View File

@ -16,8 +16,7 @@
package com.google.gson.internal.bind; 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.assertNotNull;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.TypeAdapter; import com.google.gson.TypeAdapter;
@ -51,7 +50,7 @@ public class RecursiveTypesResolveTest {
public void testRecursiveResolveSimple() { public void testRecursiveResolveSimple() {
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
TypeAdapter<Foo1> adapter = new Gson().getAdapter(Foo1.class); TypeAdapter<Foo1> adapter = new Gson().getAdapter(Foo1.class);
assertNotNull(adapter); assertThat(adapter).isNotNull();
} }
/** /**
@ -60,26 +59,26 @@ public class RecursiveTypesResolveTest {
@Test @Test
public void testDoubleSupertype() { public void testDoubleSupertype() {
assertEquals($Gson$Types.supertypeOf(Number.class), assertThat($Gson$Types.supertypeOf($Gson$Types.supertypeOf(Number.class)))
$Gson$Types.supertypeOf($Gson$Types.supertypeOf(Number.class))); .isEqualTo($Gson$Types.supertypeOf(Number.class));
} }
@Test @Test
public void testDoubleSubtype() { public void testDoubleSubtype() {
assertEquals($Gson$Types.subtypeOf(Number.class), assertThat($Gson$Types.subtypeOf($Gson$Types.subtypeOf(Number.class)))
$Gson$Types.subtypeOf($Gson$Types.subtypeOf(Number.class))); .isEqualTo($Gson$Types.subtypeOf(Number.class));
} }
@Test @Test
public void testSuperSubtype() { public void testSuperSubtype() {
assertEquals($Gson$Types.subtypeOf(Object.class), assertThat($Gson$Types.supertypeOf($Gson$Types.subtypeOf(Number.class)))
$Gson$Types.supertypeOf($Gson$Types.subtypeOf(Number.class))); .isEqualTo($Gson$Types.subtypeOf(Object.class));
} }
@Test @Test
public void testSubSupertype() { public void testSubSupertype() {
assertEquals($Gson$Types.subtypeOf(Object.class), assertThat($Gson$Types.subtypeOf($Gson$Types.supertypeOf(Number.class)))
$Gson$Types.subtypeOf($Gson$Types.supertypeOf(Number.class))); .isEqualTo($Gson$Types.subtypeOf(Object.class));
} }
/** /**
@ -97,16 +96,16 @@ public class RecursiveTypesResolveTest {
} }
@Test @Test
public void testRecursiveTypeVariablesResolve1() throws Exception { public void testRecursiveTypeVariablesResolve1() {
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
TypeAdapter<TestType> adapter = new Gson().getAdapter(TestType.class); TypeAdapter<TestType> adapter = new Gson().getAdapter(TestType.class);
assertNotNull(adapter); assertThat(adapter).isNotNull();
} }
@Test @Test
public void testRecursiveTypeVariablesResolve12() throws Exception { public void testRecursiveTypeVariablesResolve12() {
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
TypeAdapter<TestType2> adapter = new Gson().getAdapter(TestType2.class); TypeAdapter<TestType2> adapter = new Gson().getAdapter(TestType2.class);
assertNotNull(adapter); assertThat(adapter).isNotNull();
} }
} }

View File

@ -1,6 +1,6 @@
package com.google.gson.internal.bind.util; 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.assertThrows;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
@ -37,7 +37,7 @@ public class ISO8601UtilsTest {
Date date = calendar.getTime(); Date date = calendar.getTime();
String dateStr = ISO8601Utils.format(date); String dateStr = ISO8601Utils.format(date);
String expectedDate = "2018-06-25"; String expectedDate = "2018-06-25";
assertEquals(expectedDate, dateStr.substring(0, expectedDate.length())); assertThat(dateStr.substring(0, expectedDate.length())).isEqualTo(expectedDate);
} }
@Test @Test
@ -46,7 +46,7 @@ public class ISO8601UtilsTest {
Date date = new Date(time); Date date = new Date(time);
String dateStr = ISO8601Utils.format(date, true); String dateStr = ISO8601Utils.format(date, true);
String expectedDate = "2018-06-28T18:06:16.870Z"; String expectedDate = "2018-06-28T18:06:16.870Z";
assertEquals(expectedDate, dateStr); assertThat(dateStr).isEqualTo(expectedDate);
} }
@Test @Test
@ -55,7 +55,7 @@ public class ISO8601UtilsTest {
Date date = new Date(time); Date date = new Date(time);
String dateStr = ISO8601Utils.format(date, true, TimeZone.getTimeZone("Brazil/East")); String dateStr = ISO8601Utils.format(date, true, TimeZone.getTimeZone("Brazil/East"));
String expectedDate = "2018-06-28T15:06:16.870-03:00"; String expectedDate = "2018-06-28T15:06:16.870-03:00";
assertEquals(expectedDate, dateStr); assertThat(dateStr).isEqualTo(expectedDate);
} }
@Test @Test
@ -63,7 +63,7 @@ public class ISO8601UtilsTest {
String dateStr = "2018-06-25"; String dateStr = "2018-06-25";
Date date = ISO8601Utils.parse(dateStr, new ParsePosition(0)); Date date = ISO8601Utils.parse(dateStr, new ParsePosition(0));
Date expectedDate = new GregorianCalendar(2018, Calendar.JUNE, 25).getTime(); Date expectedDate = new GregorianCalendar(2018, Calendar.JUNE, 25).getTime();
assertEquals(expectedDate, date); assertThat(date).isEqualTo(expectedDate);
} }
@Test @Test
@ -93,7 +93,7 @@ public class ISO8601UtilsTest {
GregorianCalendar calendar = createUtcCalendar(); GregorianCalendar calendar = createUtcCalendar();
calendar.set(2018, Calendar.JUNE, 25, 3, 0); calendar.set(2018, Calendar.JUNE, 25, 3, 0);
Date expectedDate = calendar.getTime(); Date expectedDate = calendar.getTime();
assertEquals(expectedDate, date); assertThat(date).isEqualTo(expectedDate);
} }
@Test @Test
@ -103,11 +103,11 @@ public class ISO8601UtilsTest {
GregorianCalendar calendar = createUtcCalendar(); GregorianCalendar calendar = createUtcCalendar();
calendar.set(2018, Calendar.JUNE, 25, 3, 0); calendar.set(2018, Calendar.JUNE, 25, 3, 0);
Date expectedDate = calendar.getTime(); Date expectedDate = calendar.getTime();
assertEquals(expectedDate, date); assertThat(date).isEqualTo(expectedDate);
} }
@Test @Test
public void testDateParseInvalidTime() throws ParseException { public void testDateParseInvalidTime() {
final String dateStr = "2018-06-25T61:60:62-03:00"; final String dateStr = "2018-06-25T61:60:62-03:00";
assertThrows(ParseException.class, new ThrowingRunnable() { assertThrows(ParseException.class, new ThrowingRunnable() {
@Override @Override

View File

@ -1,9 +1,6 @@
package com.google.gson.internal.reflect; package com.google.gson.internal.reflect;
import static org.junit.Assert.assertArrayEquals; import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.lang.reflect.Constructor; import java.lang.reflect.Constructor;
import java.lang.reflect.Field; import java.lang.reflect.Field;
@ -18,18 +15,14 @@ public class Java17ReflectionHelperTest {
public void testJava17Record() throws ClassNotFoundException { public void testJava17Record() throws ClassNotFoundException {
Class<?> unixDomainPrincipalClass = Class.forName("jdk.net.UnixDomainPrincipal"); Class<?> unixDomainPrincipalClass = Class.forName("jdk.net.UnixDomainPrincipal");
// UnixDomainPrincipal is a record // UnixDomainPrincipal is a record
assertTrue(ReflectionHelper.isRecord(unixDomainPrincipalClass)); assertThat(ReflectionHelper.isRecord(unixDomainPrincipalClass)).isTrue();
// with 2 components // with 2 components
assertArrayEquals( assertThat(ReflectionHelper.getRecordComponentNames(unixDomainPrincipalClass)).isEqualTo(new String[] {"user", "group"});
new String[] {"user", "group"},
ReflectionHelper.getRecordComponentNames(unixDomainPrincipalClass));
// Check canonical constructor // Check canonical constructor
Constructor<?> constructor = Constructor<?> constructor =
ReflectionHelper.getCanonicalRecordConstructor(unixDomainPrincipalClass); ReflectionHelper.getCanonicalRecordConstructor(unixDomainPrincipalClass);
assertNotNull(constructor); assertThat(constructor).isNotNull();
assertArrayEquals( assertThat(constructor.getParameterTypes()).isEqualTo(new Class<?>[] {UserPrincipal.class, GroupPrincipal.class});
new Class<?>[] {UserPrincipal.class, GroupPrincipal.class},
constructor.getParameterTypes());
} }
@Test @Test
@ -43,14 +36,14 @@ public class Java17ReflectionHelperTest {
.newInstance(new PrincipalImpl("user"), new PrincipalImpl("group")); .newInstance(new PrincipalImpl("user"), new PrincipalImpl("group"));
String[] componentNames = ReflectionHelper.getRecordComponentNames(unixDomainPrincipalClass); String[] componentNames = ReflectionHelper.getRecordComponentNames(unixDomainPrincipalClass);
assertTrue(componentNames.length > 0); assertThat(componentNames.length > 0).isTrue();
for (String componentName : componentNames) { for (String componentName : componentNames) {
Field componentField = unixDomainPrincipalClass.getDeclaredField(componentName); Field componentField = unixDomainPrincipalClass.getDeclaredField(componentName);
Method accessor = ReflectionHelper.getAccessor(unixDomainPrincipalClass, componentField); Method accessor = ReflectionHelper.getAccessor(unixDomainPrincipalClass, componentField);
Object principal = accessor.invoke(unixDomainPrincipal); Object principal = accessor.invoke(unixDomainPrincipal);
assertEquals(new PrincipalImpl(componentName), principal); assertThat(principal).isEqualTo(new PrincipalImpl(componentName));
} }
} }

View File

@ -1,6 +1,6 @@
package com.google.gson.internal.sql; 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.Gson;
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;
@ -50,7 +50,7 @@ public class SqlTypesGsonTest {
public void testDefaultSqlDateSerialization() { public void testDefaultSqlDateSerialization() {
java.sql.Date instant = new java.sql.Date(1259875082000L); java.sql.Date instant = new java.sql.Date(1259875082000L);
String json = gson.toJson(instant); String json = gson.toJson(instant);
assertEquals("\"Dec 3, 2009\"", json); assertThat(json).isEqualTo("\"Dec 3, 2009\"");
} }
@Test @Test
@ -71,8 +71,8 @@ public class SqlTypesGsonTest {
java.sql.Date sqlDate = new java.sql.Date(0L); java.sql.Date sqlDate = new java.sql.Date(0L);
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create(); Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
String json = gson.toJson(sqlDate, Timestamp.class); String json = gson.toJson(sqlDate, Timestamp.class);
assertEquals("\"1970-01-01\"", json); assertThat(json).isEqualTo("\"1970-01-01\"");
assertEquals(0, gson.fromJson("\"1970-01-01\"", java.sql.Date.class).getTime()); assertThat(gson.fromJson("\"1970-01-01\"", java.sql.Date.class).getTime()).isEqualTo(0);
} finally { } finally {
TimeZone.setDefault(defaultTimeZone); TimeZone.setDefault(defaultTimeZone);
Locale.setDefault(defaultLocale); Locale.setDefault(defaultLocale);
@ -83,7 +83,7 @@ public class SqlTypesGsonTest {
public void testDefaultSqlTimeSerialization() { public void testDefaultSqlTimeSerialization() {
Time now = new Time(1259875082000L); Time now = new Time(1259875082000L);
String json = gson.toJson(now); String json = gson.toJson(now);
assertEquals("\"01:18:02 PM\"", json); assertThat(json).isEqualTo("\"01:18:02 PM\"");
} }
@Test @Test
@ -98,9 +98,9 @@ public class SqlTypesGsonTest {
Timestamp now = new java.sql.Timestamp(1259875082000L); Timestamp now = new java.sql.Timestamp(1259875082000L);
String json = gson.toJson(now); String json = gson.toJson(now);
if (JavaVersion.isJava9OrLater()) { if (JavaVersion.isJava9OrLater()) {
assertEquals("\"Dec 3, 2009, 1:18:02 PM\"", json); assertThat(json).isEqualTo("\"Dec 3, 2009, 1:18:02 PM\"");
} else { } 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 class SqlTypesGsonTest {
Timestamp timestamp = new Timestamp(0L); Timestamp timestamp = new Timestamp(0L);
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create(); Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
String json = gson.toJson(timestamp, Timestamp.class); String json = gson.toJson(timestamp, Timestamp.class);
assertEquals("\"1970-01-01\"", json); assertThat(json).isEqualTo("\"1970-01-01\"");
assertEquals(0, gson.fromJson("\"1970-01-01\"", Timestamp.class).getTime()); assertThat(gson.fromJson("\"1970-01-01\"", Timestamp.class).getTime()).isEqualTo(0);
} finally { } finally {
TimeZone.setDefault(defaultTimeZone); TimeZone.setDefault(defaultTimeZone);
Locale.setDefault(defaultLocale); Locale.setDefault(defaultLocale);

View File

@ -1,20 +1,19 @@
package com.google.gson.internal.sql; package com.google.gson.internal.sql;
import static org.junit.Assert.assertNotNull; import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertTrue;
import org.junit.Test; import org.junit.Test;
public class SqlTypesSupportTest { public class SqlTypesSupportTest {
@Test @Test
public void testSupported() { public void testSupported() {
assertTrue(SqlTypesSupport.SUPPORTS_SQL_TYPES); assertThat(SqlTypesSupport.SUPPORTS_SQL_TYPES).isTrue();
assertNotNull(SqlTypesSupport.DATE_DATE_TYPE); assertThat(SqlTypesSupport.DATE_DATE_TYPE).isNotNull();
assertNotNull(SqlTypesSupport.TIMESTAMP_DATE_TYPE); assertThat(SqlTypesSupport.TIMESTAMP_DATE_TYPE).isNotNull();
assertNotNull(SqlTypesSupport.DATE_FACTORY); assertThat(SqlTypesSupport.DATE_FACTORY).isNotNull();
assertNotNull(SqlTypesSupport.TIME_FACTORY); assertThat(SqlTypesSupport.TIME_FACTORY).isNotNull();
assertNotNull(SqlTypesSupport.TIMESTAMP_FACTORY); assertThat(SqlTypesSupport.TIMESTAMP_FACTORY).isNotNull();
} }
} }

View File

@ -16,8 +16,7 @@
package com.google.gson.metrics; package com.google.gson.metrics;
import static org.junit.Assert.assertEquals; import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertTrue;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.JsonParseException; import com.google.gson.JsonParseException;
@ -78,8 +77,8 @@ public class PerformanceTest {
private void parseLongJson(String json) throws JsonParseException { private void parseLongJson(String json) throws JsonParseException {
ExceptionHolder target = gson.fromJson(json, ExceptionHolder.class); ExceptionHolder target = gson.fromJson(json, ExceptionHolder.class);
assertTrue(target.message.contains("Error")); assertThat(target.message).contains("Error");
assertTrue(target.stackTrace.contains("Yippie")); assertThat(target.stackTrace).contains("Yippie");
} }
private static class ExceptionHolder { private static class ExceptionHolder {
@ -149,7 +148,7 @@ public class PerformanceTest {
String json = sb.toString(); String json = sb.toString();
Type collectionType = new TypeToken<ArrayList<CollectionEntry>>(){}.getType(); Type collectionType = new TypeToken<ArrayList<CollectionEntry>>(){}.getType();
List<CollectionEntry> list = gson.fromJson(json, collectionType); List<CollectionEntry> list = gson.fromJson(json, collectionType);
assertEquals(count, list.size()); assertThat(list).hasSize(count);
} }
/** /**

View File

@ -16,9 +16,7 @@
package com.google.gson.reflect; package com.google.gson.reflect;
import static org.junit.Assert.assertEquals; import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import java.lang.reflect.GenericArrayType; import java.lang.reflect.GenericArrayType;
@ -45,10 +43,10 @@ public final class TypeTokenTest {
@SuppressWarnings({"deprecation"}) @SuppressWarnings({"deprecation"})
@Test @Test
public void testIsAssignableFromRawTypes() { public void testIsAssignableFromRawTypes() {
assertTrue(TypeToken.get(Object.class).isAssignableFrom(String.class)); assertThat(TypeToken.get(Object.class).isAssignableFrom(String.class)).isTrue();
assertFalse(TypeToken.get(String.class).isAssignableFrom(Object.class)); assertThat(TypeToken.get(String.class).isAssignableFrom(Object.class)).isFalse();
assertTrue(TypeToken.get(RandomAccess.class).isAssignableFrom(ArrayList.class)); assertThat(TypeToken.get(RandomAccess.class).isAssignableFrom(ArrayList.class)).isTrue();
assertFalse(TypeToken.get(ArrayList.class).isAssignableFrom(RandomAccess.class)); assertThat(TypeToken.get(ArrayList.class).isAssignableFrom(RandomAccess.class)).isFalse();
} }
@SuppressWarnings({"deprecation"}) @SuppressWarnings({"deprecation"})
@ -56,13 +54,13 @@ public final class TypeTokenTest {
public void testIsAssignableFromWithTypeParameters() throws Exception { public void testIsAssignableFromWithTypeParameters() throws Exception {
Type a = getClass().getDeclaredField("listOfInteger").getGenericType(); Type a = getClass().getDeclaredField("listOfInteger").getGenericType();
Type b = getClass().getDeclaredField("listOfNumber").getGenericType(); Type b = getClass().getDeclaredField("listOfNumber").getGenericType();
assertTrue(TypeToken.get(a).isAssignableFrom(a)); assertThat(TypeToken.get(a).isAssignableFrom(a)).isTrue();
assertTrue(TypeToken.get(b).isAssignableFrom(b)); assertThat(TypeToken.get(b).isAssignableFrom(b)).isTrue();
// listOfInteger = listOfNumber; // doesn't compile; must be false // 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 // listOfNumber = listOfInteger; // doesn't compile; must be false
assertFalse(TypeToken.get(b).isAssignableFrom(a)); assertThat(TypeToken.get(b).isAssignableFrom(a)).isFalse();
} }
@SuppressWarnings({"deprecation"}) @SuppressWarnings({"deprecation"})
@ -70,14 +68,14 @@ public final class TypeTokenTest {
public void testIsAssignableFromWithBasicWildcards() throws Exception { public void testIsAssignableFromWithBasicWildcards() throws Exception {
Type a = getClass().getDeclaredField("listOfString").getGenericType(); Type a = getClass().getDeclaredField("listOfString").getGenericType();
Type b = getClass().getDeclaredField("listOfUnknown").getGenericType(); Type b = getClass().getDeclaredField("listOfUnknown").getGenericType();
assertTrue(TypeToken.get(a).isAssignableFrom(a)); assertThat(TypeToken.get(a).isAssignableFrom(a)).isTrue();
assertTrue(TypeToken.get(b).isAssignableFrom(b)); assertThat(TypeToken.get(b).isAssignableFrom(b)).isTrue();
// listOfString = listOfUnknown // doesn't compile; must be false // 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 listOfUnknown = listOfString; // compiles; must be true
// The following assertion is too difficult to support reliably, so disabling // 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"}) @SuppressWarnings({"deprecation"})
@ -85,23 +83,23 @@ public final class TypeTokenTest {
public void testIsAssignableFromWithNestedWildcards() throws Exception { public void testIsAssignableFromWithNestedWildcards() throws Exception {
Type a = getClass().getDeclaredField("listOfSetOfString").getGenericType(); Type a = getClass().getDeclaredField("listOfSetOfString").getGenericType();
Type b = getClass().getDeclaredField("listOfSetOfUnknown").getGenericType(); Type b = getClass().getDeclaredField("listOfSetOfUnknown").getGenericType();
assertTrue(TypeToken.get(a).isAssignableFrom(a)); assertThat(TypeToken.get(a).isAssignableFrom(a)).isTrue();
assertTrue(TypeToken.get(b).isAssignableFrom(b)); assertThat(TypeToken.get(b).isAssignableFrom(b)).isTrue();
// listOfSetOfString = listOfSetOfUnknown; // doesn't compile; must be false // 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 // listOfSetOfUnknown = listOfSetOfString; // doesn't compile; must be false
assertFalse(TypeToken.get(b).isAssignableFrom(a)); assertThat(TypeToken.get(b).isAssignableFrom(a)).isFalse();
} }
@Test @Test
public void testArrayFactory() { public void testArrayFactory() {
TypeToken<?> expectedStringArray = new TypeToken<String[]>() {}; TypeToken<?> expectedStringArray = new TypeToken<String[]>() {};
assertEquals(expectedStringArray, TypeToken.getArray(String.class)); assertThat(TypeToken.getArray(String.class)).isEqualTo(expectedStringArray);
TypeToken<?> expectedListOfStringArray = new TypeToken<List<String>[]>() {}; TypeToken<?> expectedListOfStringArray = new TypeToken<List<String>[]>() {};
Type listOfString = new TypeToken<List<String>>() {}.getType(); Type listOfString = new TypeToken<List<String>>() {}.getType();
assertEquals(expectedListOfStringArray, TypeToken.getArray(listOfString)); assertThat(TypeToken.getArray(listOfString)).isEqualTo(expectedListOfStringArray);
try { try {
TypeToken.getArray(null); TypeToken.getArray(null);
@ -113,24 +111,24 @@ public final class TypeTokenTest {
@Test @Test
public void testParameterizedFactory() { public void testParameterizedFactory() {
TypeToken<?> expectedListOfString = new TypeToken<List<String>>() {}; TypeToken<?> expectedListOfString = new TypeToken<List<String>>() {};
assertEquals(expectedListOfString, TypeToken.getParameterized(List.class, String.class)); assertThat(TypeToken.getParameterized(List.class, String.class)).isEqualTo(expectedListOfString);
TypeToken<?> expectedMapOfStringToString = new TypeToken<Map<String, String>>() {}; TypeToken<?> expectedMapOfStringToString = new TypeToken<Map<String, String>>() {};
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<List<List<List<String>>>>() {}; TypeToken<?> expectedListOfListOfListOfString = new TypeToken<List<List<List<String>>>>() {};
Type listOfString = TypeToken.getParameterized(List.class, String.class).getType(); Type listOfString = TypeToken.getParameterized(List.class, String.class).getType();
Type listOfListOfString = TypeToken.getParameterized(List.class, listOfString).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<GenericWithBound<Number>>() {}; TypeToken<?> expectedWithExactArg = new TypeToken<GenericWithBound<Number>>() {};
assertEquals(expectedWithExactArg, TypeToken.getParameterized(GenericWithBound.class, Number.class)); assertThat(TypeToken.getParameterized(GenericWithBound.class, Number.class)).isEqualTo(expectedWithExactArg);
TypeToken<?> expectedWithSubclassArg = new TypeToken<GenericWithBound<Integer>>() {}; TypeToken<?> expectedWithSubclassArg = new TypeToken<GenericWithBound<Integer>>() {};
assertEquals(expectedWithSubclassArg, TypeToken.getParameterized(GenericWithBound.class, Integer.class)); assertThat(TypeToken.getParameterized(GenericWithBound.class, Integer.class)).isEqualTo(expectedWithSubclassArg);
TypeToken<?> expectedSatisfyingTwoBounds = new TypeToken<GenericWithMultiBound<ClassSatisfyingBounds>>() {}; TypeToken<?> expectedSatisfyingTwoBounds = new TypeToken<GenericWithMultiBound<ClassSatisfyingBounds>>() {};
assertEquals(expectedSatisfyingTwoBounds, TypeToken.getParameterized(GenericWithMultiBound.class, ClassSatisfyingBounds.class)); assertThat(TypeToken.getParameterized(GenericWithMultiBound.class, ClassSatisfyingBounds.class)).isEqualTo(expectedSatisfyingTwoBounds);
} }
@Test @Test
@ -146,73 +144,68 @@ public final class TypeTokenTest {
TypeToken.getParameterized(arrayType, new Type[0]); TypeToken.getParameterized(arrayType, new Type[0]);
fail(); fail();
} catch (IllegalArgumentException e) { } 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 { try {
TypeToken.getParameterized(String.class, String.class); TypeToken.getParameterized(String.class, String.class);
fail(); fail();
} catch (IllegalArgumentException e) { } 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 { try {
TypeToken.getParameterized(List.class, new Type[0]); TypeToken.getParameterized(List.class, new Type[0]);
fail(); fail();
} catch (IllegalArgumentException e) { } 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 { try {
TypeToken.getParameterized(List.class, String.class, String.class); TypeToken.getParameterized(List.class, String.class, String.class);
fail(); fail();
} catch (IllegalArgumentException e) { } 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 { try {
TypeToken.getParameterized(GenericWithBound.class, String.class); TypeToken.getParameterized(GenericWithBound.class, String.class);
fail(); fail();
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
assertEquals("Type argument class java.lang.String does not satisfy bounds " assertThat(e).hasMessageThat().isEqualTo("Type argument class java.lang.String does not satisfy bounds "
+ "for type variable T declared by " + GenericWithBound.class, + "for type variable T declared by " + GenericWithBound.class);
e.getMessage());
} }
try { try {
TypeToken.getParameterized(GenericWithBound.class, Object.class); TypeToken.getParameterized(GenericWithBound.class, Object.class);
fail(); fail();
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
assertEquals("Type argument class java.lang.Object does not satisfy bounds " assertThat(e).hasMessageThat().isEqualTo("Type argument class java.lang.Object does not satisfy bounds "
+ "for type variable T declared by " + GenericWithBound.class, + "for type variable T declared by " + GenericWithBound.class);
e.getMessage());
} }
try { try {
TypeToken.getParameterized(GenericWithMultiBound.class, Number.class); TypeToken.getParameterized(GenericWithMultiBound.class, Number.class);
fail(); fail();
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
assertEquals("Type argument class java.lang.Number does not satisfy bounds " assertThat(e).hasMessageThat().isEqualTo("Type argument class java.lang.Number does not satisfy bounds "
+ "for type variable T declared by " + GenericWithMultiBound.class, + "for type variable T declared by " + GenericWithMultiBound.class);
e.getMessage());
} }
try { try {
TypeToken.getParameterized(GenericWithMultiBound.class, CharSequence.class); TypeToken.getParameterized(GenericWithMultiBound.class, CharSequence.class);
fail(); fail();
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
assertEquals("Type argument interface java.lang.CharSequence does not satisfy bounds " assertThat(e).hasMessageThat().isEqualTo("Type argument interface java.lang.CharSequence does not satisfy bounds "
+ "for type variable T declared by " + GenericWithMultiBound.class, + "for type variable T declared by " + GenericWithMultiBound.class);
e.getMessage());
} }
try { try {
TypeToken.getParameterized(GenericWithMultiBound.class, Object.class); TypeToken.getParameterized(GenericWithMultiBound.class, Object.class);
fail(); fail();
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
assertEquals("Type argument class java.lang.Object does not satisfy bounds " assertThat(e).hasMessageThat().isEqualTo("Type argument class java.lang.Object does not satisfy bounds "
+ "for type variable T declared by " + GenericWithMultiBound.class, + "for type variable T declared by " + GenericWithMultiBound.class);
e.getMessage());
} }
} }
@ -222,8 +215,8 @@ public final class TypeTokenTest {
@Test @Test
public void testTypeTokenNonAnonymousSubclass() { public void testTypeTokenNonAnonymousSubclass() {
TypeToken<?> typeToken = new CustomTypeToken(); TypeToken<?> typeToken = new CustomTypeToken();
assertEquals(String.class, typeToken.getRawType()); assertThat(typeToken.getRawType()).isEqualTo(String.class);
assertEquals(String.class, typeToken.getType()); assertThat(typeToken.getType()).isEqualTo(String.class);
} }
/** /**
@ -240,21 +233,21 @@ public final class TypeTokenTest {
new SubTypeToken<Integer>() {}; new SubTypeToken<Integer>() {};
fail(); fail();
} catch (IllegalStateException expected) { } 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 { try {
new SubSubTypeToken1<Integer>(); new SubSubTypeToken1<Integer>();
fail(); fail();
} catch (IllegalStateException expected) { } 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 { try {
new SubSubTypeToken2(); new SubSubTypeToken2();
fail(); fail();
} catch (IllegalStateException expected) { } 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 final class TypeTokenTest {
new TypeToken() {}; new TypeToken() {};
fail(); fail();
} catch (IllegalStateException expected) { } catch (IllegalStateException expected) {
assertEquals("TypeToken must be created with a type argument: new TypeToken<...>() {}; " 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.", + "When using code shrinkers (ProGuard, R8, ...) make sure that generic signatures are preserved.");
expected.getMessage());
} }
} }
} }

View File

@ -15,7 +15,7 @@
*/ */
package com.google.gson.regression; 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.Gson;
import com.google.gson.TypeAdapter; import com.google.gson.TypeAdapter;
@ -28,15 +28,15 @@ public class JsonAdapterNullSafeTest {
private final Gson gson = new Gson(); private final Gson gson = new Gson();
@Test @Test
public void testNullSafeBugSerialize() throws Exception { public void testNullSafeBugSerialize() {
Device device = new Device("ec57803e"); Device device = new Device("ec57803e");
gson.toJson(device); gson.toJson(device);
} }
@Test @Test
public void testNullSafeBugDeserialize() throws Exception { public void testNullSafeBugDeserialize() {
Device device = gson.fromJson("{'id':'ec57803e2'}", Device.class); Device device = gson.fromJson("{'id':'ec57803e2'}", Device.class);
assertEquals("ec57803e2", device.id); assertThat(device.id).isEqualTo("ec57803e2");
} }
@JsonAdapter(Device.JsonAdapterFactory.class) @JsonAdapter(Device.JsonAdapterFactory.class)

View File

@ -15,7 +15,7 @@
*/ */
package com.google.gson.regression; 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 static org.junit.Assert.fail;
import java.io.IOException; import java.io.IOException;
@ -32,7 +32,7 @@ public class OSGiTest {
public void testComGoogleGsonAnnotationsPackage() throws Exception { public void testComGoogleGsonAnnotationsPackage() throws Exception {
Manifest mf = findManifest("com.google.gson"); Manifest mf = findManifest("com.google.gson");
String importPkg = mf.getMainAttributes().getValue("Import-Package"); 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"); assertSubstring("There should be com.google.gson.annotations dependency", importPkg, "com.google.gson.annotations");
} }
@ -40,7 +40,7 @@ public class OSGiTest {
public void testSunMiscImportPackage() throws Exception { public void testSunMiscImportPackage() throws Exception {
Manifest mf = findManifest("com.google.gson"); Manifest mf = findManifest("com.google.gson");
String importPkg = mf.getMainAttributes().getValue("Import-Package"); 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(",")) { for (String dep : importPkg.split(",")) {
if (dep.contains("sun.misc")) { if (dep.contains("sun.misc")) {
assertSubstring("sun.misc import is optional", dep, "resolution:=optional"); assertSubstring("sun.misc import is optional", dep, "resolution:=optional");

View File

@ -16,7 +16,7 @@
package com.google.gson.stream; 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 static org.junit.Assume.assumeTrue;
import com.google.gson.JsonElement; import com.google.gson.JsonElement;
@ -46,155 +46,155 @@ public class JsonReaderPathTest {
@Test public void path() throws IOException { @Test public void path() throws IOException {
JsonReader reader = factory.create("{\"a\":[2,true,false,null,\"b\",{\"c\":\"d\"},[3]]}"); JsonReader reader = factory.create("{\"a\":[2,true,false,null,\"b\",{\"c\":\"d\"},[3]]}");
assertEquals("$", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$");
assertEquals("$", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$");
reader.beginObject(); reader.beginObject();
assertEquals("$.", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$.");
assertEquals("$.", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$.");
reader.nextName(); reader.nextName();
assertEquals("$.a", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$.a");
assertEquals("$.a", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$.a");
reader.beginArray(); reader.beginArray();
assertEquals("$.a[0]", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$.a[0]");
assertEquals("$.a[0]", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$.a[0]");
reader.nextInt(); reader.nextInt();
assertEquals("$.a[0]", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$.a[0]");
assertEquals("$.a[1]", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$.a[1]");
reader.nextBoolean(); reader.nextBoolean();
assertEquals("$.a[1]", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$.a[1]");
assertEquals("$.a[2]", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$.a[2]");
reader.nextBoolean(); reader.nextBoolean();
assertEquals("$.a[2]", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$.a[2]");
assertEquals("$.a[3]", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$.a[3]");
reader.nextNull(); reader.nextNull();
assertEquals("$.a[3]", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$.a[3]");
assertEquals("$.a[4]", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$.a[4]");
reader.nextString(); reader.nextString();
assertEquals("$.a[4]", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$.a[4]");
assertEquals("$.a[5]", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$.a[5]");
reader.beginObject(); reader.beginObject();
assertEquals("$.a[5].", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$.a[5].");
assertEquals("$.a[5].", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$.a[5].");
reader.nextName(); reader.nextName();
assertEquals("$.a[5].c", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$.a[5].c");
assertEquals("$.a[5].c", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$.a[5].c");
reader.nextString(); reader.nextString();
assertEquals("$.a[5].c", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$.a[5].c");
assertEquals("$.a[5].c", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$.a[5].c");
reader.endObject(); reader.endObject();
assertEquals("$.a[5]", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$.a[5]");
assertEquals("$.a[6]", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$.a[6]");
reader.beginArray(); reader.beginArray();
assertEquals("$.a[6][0]", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$.a[6][0]");
assertEquals("$.a[6][0]", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$.a[6][0]");
reader.nextInt(); reader.nextInt();
assertEquals("$.a[6][0]", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$.a[6][0]");
assertEquals("$.a[6][1]", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$.a[6][1]");
reader.endArray(); reader.endArray();
assertEquals("$.a[6]", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$.a[6]");
assertEquals("$.a[7]", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$.a[7]");
reader.endArray(); reader.endArray();
assertEquals("$.a", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$.a");
assertEquals("$.a", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$.a");
reader.endObject(); reader.endObject();
assertEquals("$", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$");
assertEquals("$", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$");
} }
@Test public void objectPath() throws IOException { @Test public void objectPath() throws IOException {
JsonReader reader = factory.create("{\"a\":1,\"b\":2}"); JsonReader reader = factory.create("{\"a\":1,\"b\":2}");
assertEquals("$", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$");
assertEquals("$", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$");
reader.peek(); reader.peek();
assertEquals("$", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$");
assertEquals("$", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$");
reader.beginObject(); reader.beginObject();
assertEquals("$.", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$.");
assertEquals("$.", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$.");
reader.peek(); reader.peek();
assertEquals("$.", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$.");
assertEquals("$.", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$.");
reader.nextName(); reader.nextName();
assertEquals("$.a", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$.a");
assertEquals("$.a", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$.a");
reader.peek(); reader.peek();
assertEquals("$.a", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$.a");
assertEquals("$.a", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$.a");
reader.nextInt(); reader.nextInt();
assertEquals("$.a", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$.a");
assertEquals("$.a", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$.a");
reader.peek(); reader.peek();
assertEquals("$.a", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$.a");
assertEquals("$.a", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$.a");
reader.nextName(); reader.nextName();
assertEquals("$.b", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$.b");
assertEquals("$.b", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$.b");
reader.peek(); reader.peek();
assertEquals("$.b", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$.b");
assertEquals("$.b", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$.b");
reader.nextInt(); reader.nextInt();
assertEquals("$.b", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$.b");
assertEquals("$.b", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$.b");
reader.peek(); reader.peek();
assertEquals("$.b", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$.b");
assertEquals("$.b", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$.b");
reader.endObject(); reader.endObject();
assertEquals("$", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$");
assertEquals("$", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$");
reader.peek(); reader.peek();
assertEquals("$", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$");
assertEquals("$", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$");
reader.close(); reader.close();
assertEquals("$", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$");
assertEquals("$", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$");
} }
@Test public void arrayPath() throws IOException { @Test public void arrayPath() throws IOException {
JsonReader reader = factory.create("[1,2]"); JsonReader reader = factory.create("[1,2]");
assertEquals("$", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$");
assertEquals("$", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$");
reader.peek(); reader.peek();
assertEquals("$", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$");
assertEquals("$", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$");
reader.beginArray(); reader.beginArray();
assertEquals("$[0]", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$[0]");
assertEquals("$[0]", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$[0]");
reader.peek(); reader.peek();
assertEquals("$[0]", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$[0]");
assertEquals("$[0]", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$[0]");
reader.nextInt(); reader.nextInt();
assertEquals("$[0]", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$[0]");
assertEquals("$[1]", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$[1]");
reader.peek(); reader.peek();
assertEquals("$[0]", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$[0]");
assertEquals("$[1]", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$[1]");
reader.nextInt(); reader.nextInt();
assertEquals("$[1]", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$[1]");
assertEquals("$[2]", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$[2]");
reader.peek(); reader.peek();
assertEquals("$[1]", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$[1]");
assertEquals("$[2]", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$[2]");
reader.endArray(); reader.endArray();
assertEquals("$", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$");
assertEquals("$", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$");
reader.peek(); reader.peek();
assertEquals("$", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$");
assertEquals("$", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$");
reader.close(); reader.close();
assertEquals("$", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$");
assertEquals("$", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$");
} }
@Test public void multipleTopLevelValuesInOneDocument() throws IOException { @Test public void multipleTopLevelValuesInOneDocument() throws IOException {
@ -204,12 +204,12 @@ public class JsonReaderPathTest {
reader.setLenient(true); reader.setLenient(true);
reader.beginArray(); reader.beginArray();
reader.endArray(); reader.endArray();
assertEquals("$", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$");
assertEquals("$", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$");
reader.beginArray(); reader.beginArray();
reader.endArray(); reader.endArray();
assertEquals("$", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$");
assertEquals("$", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$");
} }
@Test public void skipArrayElements() throws IOException { @Test public void skipArrayElements() throws IOException {
@ -217,45 +217,45 @@ public class JsonReaderPathTest {
reader.beginArray(); reader.beginArray();
reader.skipValue(); reader.skipValue();
reader.skipValue(); reader.skipValue();
assertEquals("$[1]", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$[1]");
assertEquals("$[2]", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$[2]");
} }
@Test public void skipArrayEnd() throws IOException { @Test public void skipArrayEnd() throws IOException {
JsonReader reader = factory.create("[[],1]"); JsonReader reader = factory.create("[[],1]");
reader.beginArray(); reader.beginArray();
reader.beginArray(); reader.beginArray();
assertEquals("$[0][0]", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$[0][0]");
assertEquals("$[0][0]", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$[0][0]");
reader.skipValue(); // skip end of array reader.skipValue(); // skip end of array
assertEquals("$[0]", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$[0]");
assertEquals("$[1]", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$[1]");
} }
@Test public void skipObjectNames() throws IOException { @Test public void skipObjectNames() throws IOException {
JsonReader reader = factory.create("{\"a\":[]}"); JsonReader reader = factory.create("{\"a\":[]}");
reader.beginObject(); reader.beginObject();
reader.skipValue(); reader.skipValue();
assertEquals("$.<skipped>", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$.<skipped>");
assertEquals("$.<skipped>", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$.<skipped>");
reader.beginArray(); reader.beginArray();
assertEquals("$.<skipped>[0]", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$.<skipped>[0]");
assertEquals("$.<skipped>[0]", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$.<skipped>[0]");
} }
@Test public void skipObjectValues() throws IOException { @Test public void skipObjectValues() throws IOException {
JsonReader reader = factory.create("{\"a\":1,\"b\":2}"); JsonReader reader = factory.create("{\"a\":1,\"b\":2}");
reader.beginObject(); reader.beginObject();
assertEquals("$.", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$.");
assertEquals("$.", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$.");
reader.nextName(); reader.nextName();
reader.skipValue(); reader.skipValue();
assertEquals("$.a", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$.a");
assertEquals("$.a", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$.a");
reader.nextName(); reader.nextName();
assertEquals("$.b", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$.b");
assertEquals("$.b", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$.b");
} }
@Test public void skipObjectEnd() throws IOException { @Test public void skipObjectEnd() throws IOException {
@ -263,135 +263,135 @@ public class JsonReaderPathTest {
reader.beginObject(); reader.beginObject();
reader.nextName(); reader.nextName();
reader.beginObject(); reader.beginObject();
assertEquals("$.a.", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$.a.");
assertEquals("$.a.", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$.a.");
reader.skipValue(); // skip end of object reader.skipValue(); // skip end of object
assertEquals("$.a", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$.a");
assertEquals("$.a", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$.a");
} }
@Test public void skipNestedStructures() throws IOException { @Test public void skipNestedStructures() throws IOException {
JsonReader reader = factory.create("[[1,2,3],4]"); JsonReader reader = factory.create("[[1,2,3],4]");
reader.beginArray(); reader.beginArray();
reader.skipValue(); reader.skipValue();
assertEquals("$[0]", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$[0]");
assertEquals("$[1]", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$[1]");
} }
@Test public void skipEndOfDocument() throws IOException { @Test public void skipEndOfDocument() throws IOException {
JsonReader reader = factory.create("[]"); JsonReader reader = factory.create("[]");
reader.beginArray(); reader.beginArray();
reader.endArray(); reader.endArray();
assertEquals("$", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$");
assertEquals("$", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$");
reader.skipValue(); reader.skipValue();
assertEquals("$", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$");
assertEquals("$", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$");
reader.skipValue(); reader.skipValue();
assertEquals("$", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$");
assertEquals("$", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$");
} }
@Test public void arrayOfObjects() throws IOException { @Test public void arrayOfObjects() throws IOException {
JsonReader reader = factory.create("[{},{},{}]"); JsonReader reader = factory.create("[{},{},{}]");
reader.beginArray(); reader.beginArray();
assertEquals("$[0]", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$[0]");
assertEquals("$[0]", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$[0]");
reader.beginObject(); reader.beginObject();
assertEquals("$[0].", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$[0].");
assertEquals("$[0].", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$[0].");
reader.endObject(); reader.endObject();
assertEquals("$[0]", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$[0]");
assertEquals("$[1]", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$[1]");
reader.beginObject(); reader.beginObject();
assertEquals("$[1].", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$[1].");
assertEquals("$[1].", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$[1].");
reader.endObject(); reader.endObject();
assertEquals("$[1]", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$[1]");
assertEquals("$[2]", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$[2]");
reader.beginObject(); reader.beginObject();
assertEquals("$[2].", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$[2].");
assertEquals("$[2].", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$[2].");
reader.endObject(); reader.endObject();
assertEquals("$[2]", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$[2]");
assertEquals("$[3]", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$[3]");
reader.endArray(); reader.endArray();
assertEquals("$", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$");
assertEquals("$", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$");
} }
@Test public void arrayOfArrays() throws IOException { @Test public void arrayOfArrays() throws IOException {
JsonReader reader = factory.create("[[],[],[]]"); JsonReader reader = factory.create("[[],[],[]]");
reader.beginArray(); reader.beginArray();
assertEquals("$[0]", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$[0]");
assertEquals("$[0]", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$[0]");
reader.beginArray(); reader.beginArray();
assertEquals("$[0][0]", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$[0][0]");
assertEquals("$[0][0]", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$[0][0]");
reader.endArray(); reader.endArray();
assertEquals("$[0]", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$[0]");
assertEquals("$[1]", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$[1]");
reader.beginArray(); reader.beginArray();
assertEquals("$[1][0]", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$[1][0]");
assertEquals("$[1][0]", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$[1][0]");
reader.endArray(); reader.endArray();
assertEquals("$[1]", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$[1]");
assertEquals("$[2]", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$[2]");
reader.beginArray(); reader.beginArray();
assertEquals("$[2][0]", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$[2][0]");
assertEquals("$[2][0]", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$[2][0]");
reader.endArray(); reader.endArray();
assertEquals("$[2]", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$[2]");
assertEquals("$[3]", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$[3]");
reader.endArray(); reader.endArray();
assertEquals("$", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$");
assertEquals("$", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$");
} }
@Test public void objectOfObjects() throws IOException { @Test public void objectOfObjects() throws IOException {
JsonReader reader = factory.create("{\"a\":{\"a1\":1,\"a2\":2},\"b\":{\"b1\":1}}"); JsonReader reader = factory.create("{\"a\":{\"a1\":1,\"a2\":2},\"b\":{\"b1\":1}}");
reader.beginObject(); reader.beginObject();
assertEquals("$.", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$.");
assertEquals("$.", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$.");
reader.nextName(); reader.nextName();
assertEquals("$.a", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$.a");
assertEquals("$.a", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$.a");
reader.beginObject(); reader.beginObject();
assertEquals("$.a.", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$.a.");
assertEquals("$.a.", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$.a.");
reader.nextName(); reader.nextName();
assertEquals("$.a.a1", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$.a.a1");
assertEquals("$.a.a1", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$.a.a1");
reader.nextInt(); reader.nextInt();
assertEquals("$.a.a1", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$.a.a1");
assertEquals("$.a.a1", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$.a.a1");
reader.nextName(); reader.nextName();
assertEquals("$.a.a2", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$.a.a2");
assertEquals("$.a.a2", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$.a.a2");
reader.nextInt(); reader.nextInt();
assertEquals("$.a.a2", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$.a.a2");
assertEquals("$.a.a2", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$.a.a2");
reader.endObject(); reader.endObject();
assertEquals("$.a", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$.a");
assertEquals("$.a", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$.a");
reader.nextName(); reader.nextName();
assertEquals("$.b", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$.b");
assertEquals("$.b", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$.b");
reader.beginObject(); reader.beginObject();
assertEquals("$.b.", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$.b.");
assertEquals("$.b.", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$.b.");
reader.nextName(); reader.nextName();
assertEquals("$.b.b1", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$.b.b1");
assertEquals("$.b.b1", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$.b.b1");
reader.nextInt(); reader.nextInt();
assertEquals("$.b.b1", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$.b.b1");
assertEquals("$.b.b1", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$.b.b1");
reader.endObject(); reader.endObject();
assertEquals("$.b", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$.b");
assertEquals("$.b", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$.b");
reader.endObject(); reader.endObject();
assertEquals("$", reader.getPreviousPath()); assertThat(reader.getPreviousPath()).isEqualTo("$");
assertEquals("$", reader.getPath()); assertThat(reader.getPath()).isEqualTo("$");
} }
public enum Factory { public enum Factory {

File diff suppressed because it is too large Load Diff

View File

@ -16,7 +16,7 @@
package com.google.gson.stream; 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 static org.junit.Assert.fail;
import com.google.gson.internal.LazilyParsedNumber; import com.google.gson.internal.LazilyParsedNumber;
@ -35,31 +35,31 @@ public final class JsonWriterTest {
JsonWriter writer1 = new JsonWriter(string1); JsonWriter writer1 = new JsonWriter(string1);
writer1.value(true); writer1.value(true);
writer1.close(); writer1.close();
assertEquals("true", string1.toString()); assertThat(string1.toString()).isEqualTo("true");
StringWriter string2 = new StringWriter(); StringWriter string2 = new StringWriter();
JsonWriter writer2 = new JsonWriter(string2); JsonWriter writer2 = new JsonWriter(string2);
writer2.nullValue(); writer2.nullValue();
writer2.close(); writer2.close();
assertEquals("null", string2.toString()); assertThat(string2.toString()).isEqualTo("null");
StringWriter string3 = new StringWriter(); StringWriter string3 = new StringWriter();
JsonWriter writer3 = new JsonWriter(string3); JsonWriter writer3 = new JsonWriter(string3);
writer3.value(123); writer3.value(123);
writer3.close(); writer3.close();
assertEquals("123", string3.toString()); assertThat(string3.toString()).isEqualTo("123");
StringWriter string4 = new StringWriter(); StringWriter string4 = new StringWriter();
JsonWriter writer4 = new JsonWriter(string4); JsonWriter writer4 = new JsonWriter(string4);
writer4.value(123.4); writer4.value(123.4);
writer4.close(); writer4.close();
assertEquals("123.4", string4.toString()); assertThat(string4.toString()).isEqualTo("123.4");
StringWriter string5 = new StringWriter(); StringWriter string5 = new StringWriter();
JsonWriter writert = new JsonWriter(string5); JsonWriter writert = new JsonWriter(string5);
writert.value("a"); writert.value("a");
writert.close(); writert.close();
assertEquals("\"a\"", string5.toString()); assertThat(string5.toString()).isEqualTo("\"a\"");
} }
@Test @Test
@ -170,7 +170,7 @@ public final class JsonWriterTest {
jsonWriter.name("a"); jsonWriter.name("a");
jsonWriter.value((String) null); jsonWriter.value((String) null);
jsonWriter.endObject(); jsonWriter.endObject();
assertEquals("{\"a\":null}", stringWriter.toString()); assertThat(stringWriter.toString()).isEqualTo("{\"a\":null}");
} }
@Test @Test
@ -183,7 +183,7 @@ public final class JsonWriterTest {
jsonWriter.name("c"); jsonWriter.name("c");
jsonWriter.value(1); jsonWriter.value(1);
jsonWriter.endObject(); jsonWriter.endObject();
assertEquals("{\"a\":{\"b\":true},\"c\":1}", stringWriter.toString()); assertThat(stringWriter.toString()).isEqualTo("{\"a\":{\"b\":true},\"c\":1}");
} }
@Test @Test
@ -195,19 +195,19 @@ public final class JsonWriterTest {
jsonWriter.value(Float.NaN); jsonWriter.value(Float.NaN);
fail(); fail();
} catch (IllegalArgumentException expected) { } 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 { try {
jsonWriter.value(Float.NEGATIVE_INFINITY); jsonWriter.value(Float.NEGATIVE_INFINITY);
fail(); fail();
} catch (IllegalArgumentException expected) { } 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 { try {
jsonWriter.value(Float.POSITIVE_INFINITY); jsonWriter.value(Float.POSITIVE_INFINITY);
fail(); fail();
} catch (IllegalArgumentException expected) { } 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 final class JsonWriterTest {
jsonWriter.value(Double.NaN); jsonWriter.value(Double.NaN);
fail(); fail();
} catch (IllegalArgumentException expected) { } 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 { try {
jsonWriter.value(Double.NEGATIVE_INFINITY); jsonWriter.value(Double.NEGATIVE_INFINITY);
fail(); fail();
} catch (IllegalArgumentException expected) { } 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 { try {
jsonWriter.value(Double.POSITIVE_INFINITY); jsonWriter.value(Double.POSITIVE_INFINITY);
fail(); fail();
} catch (IllegalArgumentException expected) { } 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 final class JsonWriterTest {
jsonWriter.value(Double.valueOf(Double.NaN)); jsonWriter.value(Double.valueOf(Double.NaN));
fail(); fail();
} catch (IllegalArgumentException expected) { } 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 { try {
jsonWriter.value(Double.valueOf(Double.NEGATIVE_INFINITY)); jsonWriter.value(Double.valueOf(Double.NEGATIVE_INFINITY));
fail(); fail();
} catch (IllegalArgumentException expected) { } 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 { try {
jsonWriter.value(Double.valueOf(Double.POSITIVE_INFINITY)); jsonWriter.value(Double.valueOf(Double.POSITIVE_INFINITY));
fail(); fail();
} catch (IllegalArgumentException expected) { } 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 { try {
jsonWriter.value(new LazilyParsedNumber("Infinity")); jsonWriter.value(new LazilyParsedNumber("Infinity"));
fail(); fail();
} catch (IllegalArgumentException expected) { } 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 final class JsonWriterTest {
jsonWriter.value(Float.NEGATIVE_INFINITY); jsonWriter.value(Float.NEGATIVE_INFINITY);
jsonWriter.value(Float.POSITIVE_INFINITY); jsonWriter.value(Float.POSITIVE_INFINITY);
jsonWriter.endArray(); jsonWriter.endArray();
assertEquals("[NaN,-Infinity,Infinity]", stringWriter.toString()); assertThat(stringWriter.toString()).isEqualTo("[NaN,-Infinity,Infinity]");
} }
@Test @Test
@ -290,7 +290,7 @@ public final class JsonWriterTest {
jsonWriter.value(Double.NEGATIVE_INFINITY); jsonWriter.value(Double.NEGATIVE_INFINITY);
jsonWriter.value(Double.POSITIVE_INFINITY); jsonWriter.value(Double.POSITIVE_INFINITY);
jsonWriter.endArray(); jsonWriter.endArray();
assertEquals("[NaN,-Infinity,Infinity]", stringWriter.toString()); assertThat(stringWriter.toString()).isEqualTo("[NaN,-Infinity,Infinity]");
} }
@Test @Test
@ -304,7 +304,7 @@ public final class JsonWriterTest {
jsonWriter.value(Double.valueOf(Double.POSITIVE_INFINITY)); jsonWriter.value(Double.valueOf(Double.POSITIVE_INFINITY));
jsonWriter.value(new LazilyParsedNumber("Infinity")); jsonWriter.value(new LazilyParsedNumber("Infinity"));
jsonWriter.endArray(); jsonWriter.endArray();
assertEquals("[NaN,-Infinity,Infinity,Infinity]", stringWriter.toString()); assertThat(stringWriter.toString()).isEqualTo("[NaN,-Infinity,Infinity,Infinity]");
} }
@Test @Test
@ -324,8 +324,7 @@ public final class JsonWriterTest {
jsonWriter.value((float) Math.E); jsonWriter.value((float) Math.E);
jsonWriter.endArray(); jsonWriter.endArray();
jsonWriter.close(); jsonWriter.close();
assertEquals( assertThat(stringWriter.toString()).isEqualTo("[-0.0,"
"[-0.0,"
+ "1.0," + "1.0,"
+ "3.4028235E38," + "3.4028235E38,"
+ "1.4E-45," + "1.4E-45,"
@ -334,8 +333,7 @@ public final class JsonWriterTest {
+ "2.2250739E-38," + "2.2250739E-38,"
+ "3.723379," + "3.723379,"
+ "3.1415927," + "3.1415927,"
+ "2.7182817]", + "2.7182817]");
stringWriter.toString());
} }
@Test @Test
@ -354,7 +352,7 @@ public final class JsonWriterTest {
jsonWriter.value(Math.E); jsonWriter.value(Math.E);
jsonWriter.endArray(); jsonWriter.endArray();
jsonWriter.close(); jsonWriter.close();
assertEquals("[-0.0," assertThat(stringWriter.toString()).isEqualTo("[-0.0,"
+ "1.0," + "1.0,"
+ "1.7976931348623157E308," + "1.7976931348623157E308,"
+ "4.9E-324," + "4.9E-324,"
@ -362,7 +360,7 @@ public final class JsonWriterTest {
+ "-0.5," + "-0.5,"
+ "2.2250738585072014E-308," + "2.2250738585072014E-308,"
+ "3.141592653589793," + "3.141592653589793,"
+ "2.718281828459045]", stringWriter.toString()); + "2.718281828459045]");
} }
@Test @Test
@ -377,11 +375,11 @@ public final class JsonWriterTest {
jsonWriter.value(Long.MAX_VALUE); jsonWriter.value(Long.MAX_VALUE);
jsonWriter.endArray(); jsonWriter.endArray();
jsonWriter.close(); jsonWriter.close();
assertEquals("[0," assertThat(stringWriter.toString()).isEqualTo("[0,"
+ "1," + "1,"
+ "-1," + "-1,"
+ "-9223372036854775808," + "-9223372036854775808,"
+ "9223372036854775807]", stringWriter.toString()); + "9223372036854775807]");
} }
@Test @Test
@ -395,10 +393,10 @@ public final class JsonWriterTest {
jsonWriter.value(new BigDecimal("3.141592653589793238462643383")); jsonWriter.value(new BigDecimal("3.141592653589793238462643383"));
jsonWriter.endArray(); jsonWriter.endArray();
jsonWriter.close(); jsonWriter.close();
assertEquals("[0," assertThat(stringWriter.toString()).isEqualTo("[0,"
+ "9223372036854775808," + "9223372036854775808,"
+ "-9223372036854775809," + "-9223372036854775809,"
+ "3.141592653589793238462643383]", stringWriter.toString()); + "3.141592653589793238462643383]");
} }
/** /**
@ -434,7 +432,7 @@ public final class JsonWriterTest {
jsonWriter.value(new LazilyParsedNumber(validNumber)); jsonWriter.value(new LazilyParsedNumber(validNumber));
jsonWriter.close(); jsonWriter.close();
assertEquals(validNumber, stringWriter.toString()); assertThat(stringWriter.toString()).isEqualTo(validNumber);
} }
} }
@ -473,7 +471,7 @@ public final class JsonWriterTest {
jsonWriter.value(new LazilyParsedNumber(malformedNumber)); jsonWriter.value(new LazilyParsedNumber(malformedNumber));
fail("Should have failed writing malformed number: " + malformedNumber); fail("Should have failed writing malformed number: " + malformedNumber);
} catch (IllegalArgumentException e) { } 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 final class JsonWriterTest {
jsonWriter.value(true); jsonWriter.value(true);
jsonWriter.value(false); jsonWriter.value(false);
jsonWriter.endArray(); jsonWriter.endArray();
assertEquals("[true,false]", stringWriter.toString()); assertThat(stringWriter.toString()).isEqualTo("[true,false]");
} }
@Test @Test
@ -498,7 +496,7 @@ public final class JsonWriterTest {
jsonWriter.value((Boolean) false); jsonWriter.value((Boolean) false);
jsonWriter.value((Boolean) null); jsonWriter.value((Boolean) null);
jsonWriter.endArray(); jsonWriter.endArray();
assertEquals("[true,false,null]", stringWriter.toString()); assertThat(stringWriter.toString()).isEqualTo("[true,false,null]");
} }
@Test @Test
@ -508,7 +506,7 @@ public final class JsonWriterTest {
jsonWriter.beginArray(); jsonWriter.beginArray();
jsonWriter.nullValue(); jsonWriter.nullValue();
jsonWriter.endArray(); jsonWriter.endArray();
assertEquals("[null]", stringWriter.toString()); assertThat(stringWriter.toString()).isEqualTo("[null]");
} }
@Test @Test
@ -535,7 +533,7 @@ public final class JsonWriterTest {
jsonWriter.value("\0"); jsonWriter.value("\0");
jsonWriter.value("\u0019"); jsonWriter.value("\u0019");
jsonWriter.endArray(); jsonWriter.endArray();
assertEquals("[\"a\"," assertThat(stringWriter.toString()).isEqualTo("[\"a\","
+ "\"a\\\"\"," + "\"a\\\"\","
+ "\"\\\"\"," + "\"\\\"\","
+ "\":\"," + "\":\","
@ -552,7 +550,7 @@ public final class JsonWriterTest {
+ "\"[\"," + "\"[\","
+ "\"]\"," + "\"]\","
+ "\"\\u0000\"," + "\"\\u0000\","
+ "\"\\u0019\"]", stringWriter.toString()); + "\"\\u0019\"]");
} }
@Test @Test
@ -562,7 +560,7 @@ public final class JsonWriterTest {
jsonWriter.beginArray(); jsonWriter.beginArray();
jsonWriter.value("\u2028 \u2029"); jsonWriter.value("\u2028 \u2029");
jsonWriter.endArray(); jsonWriter.endArray();
assertEquals("[\"\\u2028 \\u2029\"]", stringWriter.toString()); assertThat(stringWriter.toString()).isEqualTo("[\"\\u2028 \\u2029\"]");
} }
@Test @Test
@ -571,7 +569,7 @@ public final class JsonWriterTest {
JsonWriter jsonWriter = new JsonWriter(stringWriter); JsonWriter jsonWriter = new JsonWriter(stringWriter);
jsonWriter.beginArray(); jsonWriter.beginArray();
jsonWriter.endArray(); jsonWriter.endArray();
assertEquals("[]", stringWriter.toString()); assertThat(stringWriter.toString()).isEqualTo("[]");
} }
@Test @Test
@ -580,7 +578,7 @@ public final class JsonWriterTest {
JsonWriter jsonWriter = new JsonWriter(stringWriter); JsonWriter jsonWriter = new JsonWriter(stringWriter);
jsonWriter.beginObject(); jsonWriter.beginObject();
jsonWriter.endObject(); jsonWriter.endObject();
assertEquals("{}", stringWriter.toString()); assertThat(stringWriter.toString()).isEqualTo("{}");
} }
@Test @Test
@ -597,8 +595,8 @@ public final class JsonWriterTest {
jsonWriter.name("d").value(true); jsonWriter.name("d").value(true);
jsonWriter.endObject(); jsonWriter.endObject();
jsonWriter.endArray(); jsonWriter.endArray();
assertEquals("[{\"a\":5,\"b\":false}," assertThat(stringWriter.toString()).isEqualTo("[{\"a\":5,\"b\":false},"
+ "{\"c\":6,\"d\":true}]", stringWriter.toString()); + "{\"c\":6,\"d\":true}]");
} }
@Test @Test
@ -617,8 +615,8 @@ public final class JsonWriterTest {
jsonWriter.value(true); jsonWriter.value(true);
jsonWriter.endArray(); jsonWriter.endArray();
jsonWriter.endObject(); jsonWriter.endObject();
assertEquals("{\"a\":[5,false]," assertThat(stringWriter.toString()).isEqualTo("{\"a\":[5,false],"
+ "\"b\":[6,true]}", stringWriter.toString()); + "\"b\":[6,true]}");
} }
@Test @Test
@ -631,7 +629,7 @@ public final class JsonWriterTest {
for (int i = 0; i < 20; i++) { for (int i = 0; i < 20; i++) {
jsonWriter.endArray(); jsonWriter.endArray();
} }
assertEquals("[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]", stringWriter.toString()); assertThat(stringWriter.toString()).isEqualTo("[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]");
} }
@Test @Test
@ -647,9 +645,9 @@ public final class JsonWriterTest {
jsonWriter.endObject(); jsonWriter.endObject();
} }
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\":{" + "{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":{"
+ "}}}}}}}}}}}}}}}}}}}}}", stringWriter.toString()); + "}}}}}}}}}}}}}}}}}}}}}");
} }
@Test @Test
@ -661,7 +659,7 @@ public final class JsonWriterTest {
jsonWriter.name("a").value(false); jsonWriter.name("a").value(false);
jsonWriter.endObject(); jsonWriter.endObject();
// JsonWriter doesn't attempt to detect duplicate names // JsonWriter doesn't attempt to detect duplicate names
assertEquals("{\"a\":true,\"a\":false}", stringWriter.toString()); assertThat(stringWriter.toString()).isEqualTo("{\"a\":true,\"a\":false}");
} }
@Test @Test
@ -699,7 +697,7 @@ public final class JsonWriterTest {
+ " \"i\": 9.0\n" + " \"i\": 9.0\n"
+ " }\n" + " }\n"
+ "}"; + "}";
assertEquals(expected, stringWriter.toString()); assertThat(stringWriter.toString()).isEqualTo(expected);
} }
@Test @Test
@ -737,7 +735,7 @@ public final class JsonWriterTest {
+ " 9.0\n" + " 9.0\n"
+ " ]\n" + " ]\n"
+ "]"; + "]";
assertEquals(expected, stringWriter.toString()); assertThat(stringWriter.toString()).isEqualTo(expected);
} }
@Test @Test
@ -750,7 +748,7 @@ public final class JsonWriterTest {
writer.beginArray(); writer.beginArray();
writer.endArray(); writer.endArray();
writer.close(); writer.close();
assertEquals("[][]", stringWriter.toString()); assertThat(stringWriter.toString()).isEqualTo("[][]");
} }
@Test @Test