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);
List<JsonElement> list = a.asList();
assertThat(list.contains(new JsonPrimitive(1))).isTrue();
assertThat(list.contains(new JsonPrimitive(2))).isFalse();
assertThat(list.contains(null)).isFalse();
assertThat(list).contains(new JsonPrimitive(1));
assertThat(list).doesNotContain(new JsonPrimitive(2));
assertThat(list).doesNotContain(null);
@SuppressWarnings({"unlikely-arg-type", "CollectionIncompatibleType"})
boolean containsInt = list.contains(1); // should only contain JsonPrimitive(1)

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -15,7 +15,7 @@
*/
package com.google.gson.functional;
import static org.junit.Assert.assertFalse;
import static com.google.common.truth.Truth.assertThat;
import com.google.gson.Gson;
import java.util.concurrent.CountDownLatch;
@ -91,7 +91,7 @@ public class ConcurrencyTest {
}
startLatch.countDown();
finishedLatch.await();
assertFalse(failed.get());
assertThat(failed.get()).isFalse();
}
/**
@ -122,7 +122,7 @@ public class ConcurrencyTest {
}
startLatch.countDown();
finishedLatch.await();
assertFalse(failed.get());
assertThat(failed.get()).isFalse();
}
@SuppressWarnings("unused")

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -16,7 +16,7 @@
package com.google.gson.functional;
import static org.junit.Assert.assertEquals;
import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.fail;
import com.google.gson.Gson;
@ -55,7 +55,7 @@ public class EnumWithObfuscatedTest {
}
}
assertEquals(Gender.MALE, gson.fromJson("\"MAIL\"", Gender.class));
assertEquals("\"MAIL\"", gson.toJson(Gender.MALE, Gender.class));
assertThat(gson.fromJson("\"MAIL\"", Gender.class)).isEqualTo(Gender.MALE);
assertThat(gson.toJson(Gender.MALE, Gender.class)).isEqualTo("\"MAIL\"");
}
}

View File

@ -16,9 +16,7 @@
package com.google.gson.functional;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static com.google.common.truth.Truth.assertThat;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
@ -43,12 +41,12 @@ public class EscapingTest {
}
@Test
public void testEscapingQuotesInStringArray() throws Exception {
public void testEscapingQuotesInStringArray() {
String[] valueWithQuotes = { "beforeQuote\"afterQuote" };
String jsonRepresentation = gson.toJson(valueWithQuotes);
String[] target = gson.fromJson(jsonRepresentation, String[].class);
assertEquals(1, target.length);
assertEquals(valueWithQuotes[0], target[0]);
assertThat(target.length).isEqualTo(1);
assertThat(target[0]).isEqualTo(valueWithQuotes[0]);
}
@Test
@ -60,34 +58,33 @@ public class EscapingTest {
strings.add("&");
strings.add("'");
strings.add("\"");
assertEquals("[\"\\u003c\",\"\\u003e\",\"\\u003d\",\"\\u0026\",\"\\u0027\",\"\\\"\"]",
gson.toJson(strings));
assertThat(gson.toJson(strings)).isEqualTo("[\"\\u003c\",\"\\u003e\",\"\\u003d\",\"\\u0026\",\"\\u0027\",\"\\\"\"]");
}
@Test
public void testEscapingObjectFields() throws Exception {
public void testEscapingObjectFields() {
BagOfPrimitives objWithPrimitives = new BagOfPrimitives(1L, 1, true, "test with\" <script>");
String jsonRepresentation = gson.toJson(objWithPrimitives);
assertFalse(jsonRepresentation.contains("<"));
assertFalse(jsonRepresentation.contains(">"));
assertTrue(jsonRepresentation.contains("\\\""));
assertThat(jsonRepresentation).doesNotContain("<");
assertThat(jsonRepresentation).doesNotContain(">");
assertThat(jsonRepresentation).contains("\\\"");
BagOfPrimitives expectedObject = gson.fromJson(jsonRepresentation, BagOfPrimitives.class);
assertEquals(objWithPrimitives.getExpectedJson(), expectedObject.getExpectedJson());
assertThat(expectedObject.getExpectedJson()).isEqualTo(objWithPrimitives.getExpectedJson());
}
@Test
public void testGsonAcceptsEscapedAndNonEscapedJsonDeserialization() throws Exception {
public void testGsonAcceptsEscapedAndNonEscapedJsonDeserialization() {
Gson escapeHtmlGson = new GsonBuilder().create();
Gson noEscapeHtmlGson = new GsonBuilder().disableHtmlEscaping().create();
BagOfPrimitives target = new BagOfPrimitives(1L, 1, true, "test' / w'ith\" / \\ <script>");
String escapedJsonForm = escapeHtmlGson.toJson(target);
String nonEscapedJsonForm = noEscapeHtmlGson.toJson(target);
assertFalse(escapedJsonForm.equals(nonEscapedJsonForm));
assertThat(escapedJsonForm.equals(nonEscapedJsonForm)).isFalse();
assertEquals(target, noEscapeHtmlGson.fromJson(escapedJsonForm, BagOfPrimitives.class));
assertEquals(target, escapeHtmlGson.fromJson(nonEscapedJsonForm, BagOfPrimitives.class));
assertThat(noEscapeHtmlGson.fromJson(escapedJsonForm, BagOfPrimitives.class)).isEqualTo(target);
assertThat(escapeHtmlGson.fromJson(nonEscapedJsonForm, BagOfPrimitives.class)).isEqualTo(target);
}
@Test
@ -96,6 +93,6 @@ public class EscapingTest {
String json = gson.toJson(gson.toJson(expected));
String value = gson.fromJson(json, String.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;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static com.google.common.truth.Truth.assertThat;
import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;
@ -59,12 +56,12 @@ public class ExclusionStrategyFunctionalTest {
}
@Test
public void testExclusionStrategySerialization() throws Exception {
public void testExclusionStrategySerialization() {
Gson gson = createGson(new MyExclusionStrategy(String.class), true);
String json = gson.toJson(src);
assertFalse(json.contains("\"stringField\""));
assertFalse(json.contains("\"annotatedField\""));
assertTrue(json.contains("\"longField\""));
assertThat(json).doesNotContain("\"stringField\"");
assertThat(json).doesNotContain("\"annotatedField\"");
assertThat(json).contains("\"longField\"");
}
@Test
@ -72,13 +69,13 @@ public class ExclusionStrategyFunctionalTest {
String json = "{\"annotatedField\":1,\"stringField\":\"x\",\"longField\":2}";
Gson gson = createGson(new MyExclusionStrategy(String.class), true);
SampleObjectForTest value = gson.fromJson(json, SampleObjectForTest.class);
assertEquals(1, value.annotatedField);
assertEquals("x", value.stringField);
assertEquals(2, value.longField);
assertThat(value.annotatedField).isEqualTo(1);
assertThat(value.stringField).isEqualTo("x");
assertThat(value.longField).isEqualTo(2);
}
@Test
public void testExclusionStrategyDeserialization() throws Exception {
public void testExclusionStrategyDeserialization() {
Gson gson = createGson(new MyExclusionStrategy(String.class), false);
JsonObject json = new JsonObject();
json.add("annotatedField", new JsonPrimitive(src.annotatedField + 5));
@ -86,40 +83,40 @@ public class ExclusionStrategyFunctionalTest {
json.add("longField", new JsonPrimitive(1212311L));
SampleObjectForTest target = gson.fromJson(json, SampleObjectForTest.class);
assertEquals(1212311L, target.longField);
assertThat(target.longField).isEqualTo(1212311L);
// assert excluded fields are set to the defaults
assertEquals(src.annotatedField, target.annotatedField);
assertEquals(src.stringField, target.stringField);
assertThat(target.annotatedField).isEqualTo(src.annotatedField);
assertThat(target.stringField).isEqualTo(src.stringField);
}
@Test
public void testExclusionStrategySerializationDoesNotImpactSerialization() throws Exception {
public void testExclusionStrategySerializationDoesNotImpactSerialization() {
Gson gson = createGson(new MyExclusionStrategy(String.class), false);
String json = gson.toJson(src);
assertTrue(json.contains("\"stringField\""));
assertTrue(json.contains("\"annotatedField\""));
assertTrue(json.contains("\"longField\""));
assertThat(json).contains("\"stringField\"");
assertThat(json).contains("\"annotatedField\"");
assertThat(json).contains("\"longField\"");
}
@Test
public void testExclusionStrategyWithMode() throws Exception {
public void testExclusionStrategyWithMode() {
SampleObjectForTest testObj = new SampleObjectForTest(
src.annotatedField + 5, src.stringField + "blah,blah",
src.longField + 655L);
Gson gson = createGson(new MyExclusionStrategy(String.class), false);
JsonObject json = gson.toJsonTree(testObj).getAsJsonObject();
assertEquals(testObj.annotatedField, json.get("annotatedField").getAsInt());
assertEquals(testObj.stringField, json.get("stringField").getAsString());
assertEquals(testObj.longField, json.get("longField").getAsLong());
assertThat(json.get("annotatedField").getAsInt()).isEqualTo(testObj.annotatedField);
assertThat(json.get("stringField").getAsString()).isEqualTo(testObj.stringField);
assertThat(json.get("longField").getAsLong()).isEqualTo(testObj.longField);
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
assertEquals(src.annotatedField, target.annotatedField);
assertEquals(src.stringField, target.stringField);
assertThat(target.annotatedField).isEqualTo(src.annotatedField);
assertThat(target.stringField).isEqualTo(src.stringField);
}
@Test
@ -127,7 +124,7 @@ public class ExclusionStrategyFunctionalTest {
Gson gson = new GsonBuilder()
.addSerializationExclusionStrategy(EXCLUDE_SAMPLE_OBJECT_FOR_TEST)
.create();
assertEquals("null", gson.toJson(new SampleObjectForTest(), SampleObjectForTest.class));
assertThat(gson.toJson(new SampleObjectForTest(), SampleObjectForTest.class)).isEqualTo("null");
}
@Test
@ -137,9 +134,9 @@ public class ExclusionStrategyFunctionalTest {
.create();
String json = "{\"annotatedField\":1,\"stringField\":\"x\",\"longField\":2}";
SampleObjectForTest value = gson.fromJson(json, SampleObjectForTest.class);
assertEquals(1, value.annotatedField);
assertEquals("x", value.stringField);
assertEquals(2, value.longField);
assertThat(value.annotatedField).isEqualTo(1);
assertThat(value.stringField).isEqualTo("x");
assertThat(value.longField).isEqualTo(2);
}
@Test
@ -149,7 +146,7 @@ public class ExclusionStrategyFunctionalTest {
.create();
String json = "{\"annotatedField\":1,\"stringField\":\"x\",\"longField\":2}";
SampleObjectForTest value = gson.fromJson(json, SampleObjectForTest.class);
assertNull(value);
assertThat(value).isNull();
}
@Test
@ -158,9 +155,9 @@ public class ExclusionStrategyFunctionalTest {
.addDeserializationExclusionStrategy(EXCLUDE_SAMPLE_OBJECT_FOR_TEST)
.create();
String json = gson.toJson(new SampleObjectForTest(), SampleObjectForTest.class);
assertTrue(json.contains("\"stringField\""));
assertTrue(json.contains("\"annotatedField\""));
assertTrue(json.contains("\"longField\""));
assertThat(json).contains("\"stringField\"");
assertThat(json).contains("\"annotatedField\"");
assertThat(json).contains("\"longField\"");
}
private static Gson createGson(ExclusionStrategy exclusionStrategy, boolean serialization) {

View File

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

View File

@ -16,7 +16,7 @@
package com.google.gson.functional;
import static org.junit.Assert.assertEquals;
import static com.google.common.truth.Truth.assertThat;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
@ -41,37 +41,37 @@ public class FieldExclusionTest {
}
@Test
public void testDefaultInnerClassExclusion() throws Exception {
public void testDefaultInnerClassExclusion() {
Gson gson = new Gson();
Outer.Inner target = outer.new Inner(VALUE);
String result = gson.toJson(target);
assertEquals(target.toJson(), result);
assertThat(result).isEqualTo(target.toJson());
gson = new GsonBuilder().create();
target = outer.new Inner(VALUE);
result = gson.toJson(target);
assertEquals(target.toJson(), result);
assertThat(result).isEqualTo(target.toJson());
}
@Test
public void testInnerClassExclusion() throws Exception {
public void testInnerClassExclusion() {
Gson gson = new GsonBuilder().disableInnerClassSerialization().create();
Outer.Inner target = outer.new Inner(VALUE);
String result = gson.toJson(target);
assertEquals("null", result);
assertThat(result).isEqualTo("null");
}
@Test
public void testDefaultNestedStaticClassIncluded() throws Exception {
public void testDefaultNestedStaticClassIncluded() {
Gson gson = new Gson();
Outer.Inner target = outer.new Inner(VALUE);
String result = gson.toJson(target);
assertEquals(target.toJson(), result);
assertThat(result).isEqualTo(target.toJson());
gson = new GsonBuilder().create();
target = outer.new Inner(VALUE);
result = gson.toJson(target);
assertEquals(target.toJson(), result);
assertThat(result).isEqualTo(target.toJson());
}
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_WITH_SPACES;
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.Gson;
@ -34,55 +34,55 @@ public final class FieldNamingTest {
@Test
public void testIdentity() {
Gson gson = getGsonWithNamingPolicy(IDENTITY);
assertEquals("{'lowerCamel':1,'UpperCamel':2,'_lowerCamelLeadingUnderscore':3," +
"'_UpperCamelLeadingUnderscore':4,'lower_words':5,'UPPER_WORDS':6," +
"'annotatedName':7,'lowerId':8,'_9':9}",
gson.toJson(new TestNames()).replace('\"', '\''));
assertThat(gson.toJson(new TestNames()).replace('\"', '\''))
.isEqualTo("{'lowerCamel':1,'UpperCamel':2,'_lowerCamelLeadingUnderscore':3," +
"'_UpperCamelLeadingUnderscore':4,'lower_words':5,'UPPER_WORDS':6," +
"'annotatedName':7,'lowerId':8,'_9':9}");
}
@Test
public void testUpperCamelCase() {
Gson gson = getGsonWithNamingPolicy(UPPER_CAMEL_CASE);
assertEquals("{'LowerCamel':1,'UpperCamel':2,'_LowerCamelLeadingUnderscore':3," +
"'_UpperCamelLeadingUnderscore':4,'Lower_words':5,'UPPER_WORDS':6," +
"'annotatedName':7,'LowerId':8,'_9':9}",
gson.toJson(new TestNames()).replace('\"', '\''));
assertThat(gson.toJson(new TestNames()).replace('\"', '\''))
.isEqualTo("{'LowerCamel':1,'UpperCamel':2,'_LowerCamelLeadingUnderscore':3," +
"'_UpperCamelLeadingUnderscore':4,'Lower_words':5,'UPPER_WORDS':6," +
"'annotatedName':7,'LowerId':8,'_9':9}");
}
@Test
public void testUpperCamelCaseWithSpaces() {
Gson gson = getGsonWithNamingPolicy(UPPER_CAMEL_CASE_WITH_SPACES);
assertEquals("{'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," +
"'annotatedName':7,'Lower Id':8,'_9':9}",
gson.toJson(new TestNames()).replace('\"', '\''));
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," +
"'annotatedName':7,'Lower Id':8,'_9':9}");
}
@Test
public void testUpperCaseWithUnderscores() {
Gson gson = getGsonWithNamingPolicy(UPPER_CASE_WITH_UNDERSCORES);
assertEquals("{'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," +
"'annotatedName':7,'LOWER_ID':8,'_9':9}",
gson.toJson(new TestNames()).replace('\"', '\''));
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," +
"'annotatedName':7,'LOWER_ID':8,'_9':9}");
}
@Test
public void testLowerCaseWithUnderscores() {
Gson gson = getGsonWithNamingPolicy(LOWER_CASE_WITH_UNDERSCORES);
assertEquals("{'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," +
"'annotatedName':7,'lower_id':8,'_9':9}",
gson.toJson(new TestNames()).replace('\"', '\''));
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," +
"'annotatedName':7,'lower_id':8,'_9':9}");
}
@Test
public void testLowerCaseWithDashes() {
Gson gson = getGsonWithNamingPolicy(LOWER_CASE_WITH_DASHES);
assertEquals("{'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," +
"'annotatedName':7,'lower-id':8,'_9':9}",
gson.toJson(new TestNames()).replace('\"', '\''));
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," +
"'annotatedName':7,'lower-id':8,'_9':9}");
}
private Gson getGsonWithNamingPolicy(FieldNamingPolicy fieldNamingPolicy){

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -15,8 +15,7 @@
*/
package com.google.gson.internal;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static com.google.common.truth.Truth.assertThat;
import org.junit.Test;
@ -30,51 +29,51 @@ public class JavaVersionTest {
@Test
public void testGetMajorJavaVersion() {
assertTrue(JavaVersion.getMajorJavaVersion() >= 7); // Gson currently requires at least Java 7
assertThat(JavaVersion.getMajorJavaVersion() >= 7).isTrue(); // Gson currently requires at least Java 7
}
@Test
public void testJava6() {
assertEquals(6, JavaVersion.getMajorJavaVersion("1.6.0")); // http://www.oracle.com/technetwork/java/javase/version-6-141920.html
assertThat(JavaVersion.getMajorJavaVersion("1.6.0")).isEqualTo(6); // http://www.oracle.com/technetwork/java/javase/version-6-141920.html
}
@Test
public void testJava7() {
assertEquals(7, JavaVersion.getMajorJavaVersion("1.7.0")); // http://www.oracle.com/technetwork/java/javase/jdk7-naming-418744.html
assertThat(JavaVersion.getMajorJavaVersion("1.7.0")).isEqualTo(7); // http://www.oracle.com/technetwork/java/javase/jdk7-naming-418744.html
}
@Test
public void testJava8() {
assertEquals(8, JavaVersion.getMajorJavaVersion("1.8"));
assertEquals(8, JavaVersion.getMajorJavaVersion("1.8.0"));
assertEquals(8, JavaVersion.getMajorJavaVersion("1.8.0_131"));
assertEquals(8, JavaVersion.getMajorJavaVersion("1.8.0_60-ea"));
assertEquals(8, JavaVersion.getMajorJavaVersion("1.8.0_111-internal"));
assertThat(JavaVersion.getMajorJavaVersion("1.8")).isEqualTo(8);
assertThat(JavaVersion.getMajorJavaVersion("1.8.0")).isEqualTo(8);
assertThat(JavaVersion.getMajorJavaVersion("1.8.0_131")).isEqualTo(8);
assertThat(JavaVersion.getMajorJavaVersion("1.8.0_60-ea")).isEqualTo(8);
assertThat(JavaVersion.getMajorJavaVersion("1.8.0_111-internal")).isEqualTo(8);
// openjdk8 per https://github.com/AdoptOpenJDK/openjdk-build/issues/93
assertEquals(8, JavaVersion.getMajorJavaVersion("1.8.0-internal"));
assertEquals(8, JavaVersion.getMajorJavaVersion("1.8.0_131-adoptopenjdk"));
assertThat(JavaVersion.getMajorJavaVersion("1.8.0-internal")).isEqualTo(8);
assertThat(JavaVersion.getMajorJavaVersion("1.8.0_131-adoptopenjdk")).isEqualTo(8);
}
@Test
public void testJava9() {
// Legacy style
assertEquals(9, JavaVersion.getMajorJavaVersion("9.0.4")); // Oracle JDK 9
assertEquals(9, JavaVersion.getMajorJavaVersion("9-Debian")); // Debian as reported in https://github.com/google/gson/issues/1310
assertThat(JavaVersion.getMajorJavaVersion("9.0.4")).isEqualTo(9); // Oracle JDK 9
assertThat(JavaVersion.getMajorJavaVersion("9-Debian")).isEqualTo(9); // Debian as reported in https://github.com/google/gson/issues/1310
// New style
assertEquals(9, JavaVersion.getMajorJavaVersion("9-ea+19"));
assertEquals(9, JavaVersion.getMajorJavaVersion("9+100"));
assertEquals(9, JavaVersion.getMajorJavaVersion("9.0.1+20"));
assertEquals(9, JavaVersion.getMajorJavaVersion("9.1.1+20"));
assertThat(JavaVersion.getMajorJavaVersion("9-ea+19")).isEqualTo(9);
assertThat(JavaVersion.getMajorJavaVersion("9+100")).isEqualTo(9);
assertThat(JavaVersion.getMajorJavaVersion("9.0.1+20")).isEqualTo(9);
assertThat(JavaVersion.getMajorJavaVersion("9.1.1+20")).isEqualTo(9);
}
@Test
public void testJava10() {
assertEquals(10, JavaVersion.getMajorJavaVersion("10.0.1")); // Oracle JDK 10.0.1
assertThat(JavaVersion.getMajorJavaVersion("10.0.1")).isEqualTo(10); // Oracle JDK 10.0.1
}
@Test
public void testUnknownVersionFormat() {
assertEquals(6, JavaVersion.getMajorJavaVersion("Java9")); // unknown format
assertThat(JavaVersion.getMajorJavaVersion("Java9")).isEqualTo(6); // unknown format
}
}

View File

@ -15,8 +15,7 @@
*/
package com.google.gson.internal;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static com.google.common.truth.Truth.assertThat;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
@ -31,14 +30,14 @@ public class LazilyParsedNumberTest {
public void testHashCode() {
LazilyParsedNumber n1 = new LazilyParsedNumber("1");
LazilyParsedNumber n1Another = new LazilyParsedNumber("1");
assertEquals(n1.hashCode(), n1Another.hashCode());
assertThat(n1Another.hashCode()).isEqualTo(n1.hashCode());
}
@Test
public void testEquals() {
LazilyParsedNumber n1 = new LazilyParsedNumber("1");
LazilyParsedNumber n1Another = new LazilyParsedNumber("1");
assertTrue(n1.equals(n1Another));
assertThat(n1.equals(n1Another)).isTrue();
}
@Test
@ -50,6 +49,6 @@ public class LazilyParsedNumberTest {
ObjectInputStream objIn = new ObjectInputStream(new ByteArrayInputStream(out.toByteArray()));
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;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.fail;
import com.google.gson.common.MoreAsserts;
@ -86,10 +83,11 @@ public final class LinkedTreeMapTest {
public void testPutNullValue() {
LinkedTreeMap<String, String> map = new LinkedTreeMap<>();
map.put("a", null);
assertEquals(1, map.size());
assertTrue(map.containsKey("a"));
assertTrue(map.containsValue(null));
assertNull(map.get("a"));
assertThat(map).hasSize(1);
assertThat(map.containsKey("a")).isTrue();
assertThat(map.containsValue(null)).isTrue();
assertThat(map.get("a")).isNull();
}
@Test
@ -99,27 +97,27 @@ public final class LinkedTreeMapTest {
map.put("a", null);
fail();
} catch (NullPointerException e) {
assertEquals("value == null", e.getMessage());
assertThat(e.getMessage()).isEqualTo("value == null");
}
assertEquals(0, map.size());
assertFalse(map.containsKey("a"));
assertFalse(map.containsValue(null));
assertThat(map).hasSize(0);
assertThat(map).doesNotContainKey("a");
assertThat(map.containsValue(null)).isFalse();
}
@Test
public void testEntrySetValueNull() {
LinkedTreeMap<String, String> map = new LinkedTreeMap<>();
map.put("a", "1");
assertEquals("1", map.get("a"));
assertThat(map.get("a")).isEqualTo("1");
Entry<String, String> entry = map.entrySet().iterator().next();
assertEquals("a", entry.getKey());
assertEquals("1", entry.getValue());
assertThat(entry.getKey()).isEqualTo("a");
assertThat(entry.getValue()).isEqualTo("1");
entry.setValue(null);
assertNull(entry.getValue());
assertThat(entry.getValue()).isNull();
assertTrue(map.containsKey("a"));
assertTrue(map.containsValue(null));
assertNull(map.get("a"));
assertThat(map.containsKey("a")).isTrue();
assertThat(map.containsValue(null)).isTrue();
assertThat(map.get("a")).isNull();
}
@ -132,47 +130,47 @@ public final class LinkedTreeMapTest {
entry.setValue(null);
fail();
} catch (NullPointerException e) {
assertEquals("value == null", e.getMessage());
assertThat(e.getMessage()).isEqualTo("value == null");
}
assertEquals("1", entry.getValue());
assertEquals("1", map.get("a"));
assertFalse(map.containsValue(null));
assertThat(entry.getValue()).isEqualTo("1");
assertThat(map.get("a")).isEqualTo("1");
assertThat(map.containsValue(null)).isFalse();
}
@Test
public void testContainsNonComparableKeyReturnsFalse() {
LinkedTreeMap<String, String> map = new LinkedTreeMap<>();
map.put("a", "android");
assertFalse(map.containsKey(new Object()));
assertThat(map).doesNotContainKey(new Object());
}
@Test
public void testContainsNullKeyIsAlwaysFalse() {
LinkedTreeMap<String, String> map = new LinkedTreeMap<>();
assertFalse(map.containsKey(null));
assertThat(map.containsKey(null)).isFalse();
map.put("a", "android");
assertFalse(map.containsKey(null));
assertThat(map.containsKey(null)).isFalse();
}
@Test
public void testPutOverrides() throws Exception {
LinkedTreeMap<String, String> map = new LinkedTreeMap<>();
assertNull(map.put("d", "donut"));
assertNull(map.put("e", "eclair"));
assertNull(map.put("f", "froyo"));
assertEquals(3, map.size());
assertThat(map.put("d", "donut")).isNull();
assertThat(map.put("e", "eclair")).isNull();
assertThat(map.put("f", "froyo")).isNull();
assertThat(map).hasSize(3);
assertEquals("donut", map.get("d"));
assertEquals("donut", map.put("d", "done"));
assertEquals(3, map.size());
assertThat(map.get("d")).isEqualTo("donut");
assertThat(map.put("d", "done")).isEqualTo("donut");
assertThat(map).hasSize(3);
}
@Test
public void testEmptyStringValues() {
LinkedTreeMap<String, String> map = new LinkedTreeMap<>();
map.put("a", "");
assertTrue(map.containsKey("a"));
assertEquals("", map.get("a"));
assertThat(map.containsKey("a")).isTrue();
assertThat(map.get("a")).isEqualTo("");
}
@Test
@ -187,8 +185,8 @@ public final class LinkedTreeMapTest {
for (int i = 0; i < keys.length; i++) {
String key = keys[i];
assertTrue(map.containsKey(key));
assertEquals("" + i, map.get(key));
assertThat(map.containsKey(key)).isTrue();
assertThat(map.get(key)).isEqualTo("" + i);
}
}
@ -200,7 +198,7 @@ public final class LinkedTreeMapTest {
map.put("b", "bbq");
map.clear();
assertIterationOrder(map.keySet());
assertEquals(0, map.size());
assertThat(map).hasSize(0);
}
@Test
@ -232,7 +230,7 @@ public final class LinkedTreeMapTest {
ObjectInputStream objIn = new ObjectInputStream(new ByteArrayInputStream(out.toByteArray()));
@SuppressWarnings("unchecked")
Map<String, Integer> deserialized = (Map<String, Integer>) objIn.readObject();
assertEquals(Collections.singletonMap("a", 1), deserialized);
assertThat(deserialized).isEqualTo(Collections.singletonMap("a", 1));
}
@SuppressWarnings("varargs")
@ -242,6 +240,6 @@ public final class LinkedTreeMapTest {
for (T t : actual) {
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;
import static org.junit.Assert.assertEquals;
import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.fail;
import java.io.IOException;
@ -57,12 +57,12 @@ public class StreamsTest {
}
String actualOutput = stringBuilder.toString();
assertEquals("a\u1234testnullcdul,a\u1234\u1234,charsha,stringtr", actualOutput);
assertThat(actualOutput).isEqualTo("a\u1234testnullcdul,a\u1234\u1234,charsha,stringtr");
writer.flush();
writer.close();
// flush() and close() calls should have had no effect
assertEquals(actualOutput, stringBuilder.toString());
assertThat(stringBuilder.toString()).isEqualTo(actualOutput);
}
}

View File

@ -15,8 +15,7 @@
*/
package com.google.gson.internal;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.fail;
import org.junit.Test;
@ -46,7 +45,7 @@ public final class UnsafeAllocatorInstantiationTest {
UnsafeAllocator.INSTANCE.newInstance(Interface.class);
fail();
} catch (AssertionError e) {
assertTrue(e.getMessage().startsWith("UnsafeAllocator is used for non-instantiable type"));
assertThat(e).hasMessageThat().startsWith("UnsafeAllocator is used for non-instantiable type");
}
}
@ -60,7 +59,7 @@ public final class UnsafeAllocatorInstantiationTest {
UnsafeAllocator.INSTANCE.newInstance(AbstractClass.class);
fail();
} catch (AssertionError e) {
assertTrue(e.getMessage().startsWith("UnsafeAllocator is used for non-instantiable type"));
assertThat(e).hasMessageThat().startsWith("UnsafeAllocator is used for non-instantiable type");
}
}
@ -70,6 +69,6 @@ public final class UnsafeAllocatorInstantiationTest {
@Test
public void testConcreteClassInstantiation() throws Exception {
ConcreteClass instance = UnsafeAllocator.INSTANCE.newInstance(ConcreteClass.class);
assertNotNull(instance);
assertThat(instance).isNotNull();
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -16,8 +16,7 @@
package com.google.gson.internal.bind;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static com.google.common.truth.Truth.assertThat;
import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
@ -51,7 +50,7 @@ public class RecursiveTypesResolveTest {
public void testRecursiveResolveSimple() {
@SuppressWarnings("rawtypes")
TypeAdapter<Foo1> adapter = new Gson().getAdapter(Foo1.class);
assertNotNull(adapter);
assertThat(adapter).isNotNull();
}
/**
@ -60,26 +59,26 @@ public class RecursiveTypesResolveTest {
@Test
public void testDoubleSupertype() {
assertEquals($Gson$Types.supertypeOf(Number.class),
$Gson$Types.supertypeOf($Gson$Types.supertypeOf(Number.class)));
assertThat($Gson$Types.supertypeOf($Gson$Types.supertypeOf(Number.class)))
.isEqualTo($Gson$Types.supertypeOf(Number.class));
}
@Test
public void testDoubleSubtype() {
assertEquals($Gson$Types.subtypeOf(Number.class),
$Gson$Types.subtypeOf($Gson$Types.subtypeOf(Number.class)));
assertThat($Gson$Types.subtypeOf($Gson$Types.subtypeOf(Number.class)))
.isEqualTo($Gson$Types.subtypeOf(Number.class));
}
@Test
public void testSuperSubtype() {
assertEquals($Gson$Types.subtypeOf(Object.class),
$Gson$Types.supertypeOf($Gson$Types.subtypeOf(Number.class)));
assertThat($Gson$Types.supertypeOf($Gson$Types.subtypeOf(Number.class)))
.isEqualTo($Gson$Types.subtypeOf(Object.class));
}
@Test
public void testSubSupertype() {
assertEquals($Gson$Types.subtypeOf(Object.class),
$Gson$Types.subtypeOf($Gson$Types.supertypeOf(Number.class)));
assertThat($Gson$Types.subtypeOf($Gson$Types.supertypeOf(Number.class)))
.isEqualTo($Gson$Types.subtypeOf(Object.class));
}
/**
@ -97,16 +96,16 @@ public class RecursiveTypesResolveTest {
}
@Test
public void testRecursiveTypeVariablesResolve1() throws Exception {
public void testRecursiveTypeVariablesResolve1() {
@SuppressWarnings("rawtypes")
TypeAdapter<TestType> adapter = new Gson().getAdapter(TestType.class);
assertNotNull(adapter);
assertThat(adapter).isNotNull();
}
@Test
public void testRecursiveTypeVariablesResolve12() throws Exception {
public void testRecursiveTypeVariablesResolve12() {
@SuppressWarnings("rawtypes")
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;
import static org.junit.Assert.assertEquals;
import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.fail;
@ -37,7 +37,7 @@ public class ISO8601UtilsTest {
Date date = calendar.getTime();
String dateStr = ISO8601Utils.format(date);
String expectedDate = "2018-06-25";
assertEquals(expectedDate, dateStr.substring(0, expectedDate.length()));
assertThat(dateStr.substring(0, expectedDate.length())).isEqualTo(expectedDate);
}
@Test
@ -46,7 +46,7 @@ public class ISO8601UtilsTest {
Date date = new Date(time);
String dateStr = ISO8601Utils.format(date, true);
String expectedDate = "2018-06-28T18:06:16.870Z";
assertEquals(expectedDate, dateStr);
assertThat(dateStr).isEqualTo(expectedDate);
}
@Test
@ -55,7 +55,7 @@ public class ISO8601UtilsTest {
Date date = new Date(time);
String dateStr = ISO8601Utils.format(date, true, TimeZone.getTimeZone("Brazil/East"));
String expectedDate = "2018-06-28T15:06:16.870-03:00";
assertEquals(expectedDate, dateStr);
assertThat(dateStr).isEqualTo(expectedDate);
}
@Test
@ -63,7 +63,7 @@ public class ISO8601UtilsTest {
String dateStr = "2018-06-25";
Date date = ISO8601Utils.parse(dateStr, new ParsePosition(0));
Date expectedDate = new GregorianCalendar(2018, Calendar.JUNE, 25).getTime();
assertEquals(expectedDate, date);
assertThat(date).isEqualTo(expectedDate);
}
@Test
@ -93,7 +93,7 @@ public class ISO8601UtilsTest {
GregorianCalendar calendar = createUtcCalendar();
calendar.set(2018, Calendar.JUNE, 25, 3, 0);
Date expectedDate = calendar.getTime();
assertEquals(expectedDate, date);
assertThat(date).isEqualTo(expectedDate);
}
@Test
@ -103,11 +103,11 @@ public class ISO8601UtilsTest {
GregorianCalendar calendar = createUtcCalendar();
calendar.set(2018, Calendar.JUNE, 25, 3, 0);
Date expectedDate = calendar.getTime();
assertEquals(expectedDate, date);
assertThat(date).isEqualTo(expectedDate);
}
@Test
public void testDateParseInvalidTime() throws ParseException {
public void testDateParseInvalidTime() {
final String dateStr = "2018-06-25T61:60:62-03:00";
assertThrows(ParseException.class, new ThrowingRunnable() {
@Override

View File

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

View File

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

View File

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

View File

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

View File

@ -15,7 +15,7 @@
*/
package com.google.gson.regression;
import static org.junit.Assert.assertEquals;
import static com.google.common.truth.Truth.assertThat;
import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
@ -28,15 +28,15 @@ public class JsonAdapterNullSafeTest {
private final Gson gson = new Gson();
@Test
public void testNullSafeBugSerialize() throws Exception {
public void testNullSafeBugSerialize() {
Device device = new Device("ec57803e");
gson.toJson(device);
}
@Test
public void testNullSafeBugDeserialize() throws Exception {
public void testNullSafeBugDeserialize() {
Device device = gson.fromJson("{'id':'ec57803e2'}", Device.class);
assertEquals("ec57803e2", device.id);
assertThat(device.id).isEqualTo("ec57803e2");
}
@JsonAdapter(Device.JsonAdapterFactory.class)

View File

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

View File

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

File diff suppressed because it is too large Load Diff

View File

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