Port Junit test to Truth in the package `com.google.gson` of the module `gson` (#2299)

* Add the Truth dependency

* Port Junit test to Truth in the package `com.google.gson` of the module `gson`

* Replace the `assertThat(e.getMessage()).isEqualTo(...)"` with `assertThat(e).hasMessageThat().isEqualTo(...)`

* Minor fixes
This commit is contained in:
Maicol 2023-01-17 16:59:10 +01:00 committed by GitHub
parent d7fb0e4a31
commit be87c3fd0e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
31 changed files with 659 additions and 688 deletions

View File

@ -27,6 +27,12 @@
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.truth</groupId>
<artifactId>truth</artifactId>
<version>1.1.3</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>

View File

@ -16,10 +16,9 @@
package com.google.gson;
import static org.junit.Assert.assertEquals;
import static com.google.common.truth.Truth.assertThat;
import com.google.gson.reflect.TypeToken;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
@ -43,6 +42,6 @@ public final class CommentsTest {
+ "]";
List<String> abc = new Gson().fromJson(json, new TypeToken<List<String>>() {}.getType());
assertEquals(Arrays.asList("a", "b", "c"), abc);
assertThat(abc).containsExactly("a", "b", "c").inOrder();
}
}

View File

@ -16,7 +16,7 @@
package com.google.gson;
import static org.junit.Assert.assertEquals;
import static com.google.common.truth.Truth.assertThat;
import java.net.InetAddress;
import org.junit.Before;
@ -39,9 +39,9 @@ public class DefaultInetAddressTypeAdapterTest {
public void testInetAddressSerializationAndDeserialization() throws Exception {
InetAddress address = InetAddress.getByName("8.8.8.8");
String jsonAddress = gson.toJson(address);
assertEquals("\"8.8.8.8\"", jsonAddress);
assertThat(jsonAddress).isEqualTo("\"8.8.8.8\"");
InetAddress value = gson.fromJson(jsonAddress, InetAddress.class);
assertEquals(value, address);
}
assertThat(address).isEqualTo(value);
}
}

View File

@ -16,7 +16,7 @@
package com.google.gson;
import static org.junit.Assert.assertTrue;
import static com.google.common.truth.Truth.assertThat;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
@ -37,9 +37,9 @@ public class DefaultMapJsonSerializerTest {
public void testEmptyMapNoTypeSerialization() {
Map<String, String> emptyMap = new HashMap<>();
JsonElement element = gson.toJsonTree(emptyMap, emptyMap.getClass());
assertTrue(element instanceof JsonObject);
assertThat(element).isInstanceOf(JsonObject.class);
JsonObject emptyMapJsonObject = (JsonObject) element;
assertTrue(emptyMapJsonObject.entrySet().isEmpty());
assertThat(emptyMapJsonObject.entrySet()).isEmpty();
}
@Test
@ -48,9 +48,9 @@ public class DefaultMapJsonSerializerTest {
Map<String, String> emptyMap = new HashMap<>();
JsonElement element = gson.toJsonTree(emptyMap, mapType);
assertTrue(element instanceof JsonObject);
assertThat(element).isInstanceOf(JsonObject.class);
JsonObject emptyMapJsonObject = (JsonObject) element;
assertTrue(emptyMapJsonObject.entrySet().isEmpty());
assertThat(emptyMapJsonObject.entrySet()).isEmpty();
}
@Test
@ -62,8 +62,8 @@ public class DefaultMapJsonSerializerTest {
Gson gson = new Gson();
JsonElement element = gson.toJsonTree(myMap, mapType);
assertTrue(element.isJsonObject());
assertThat(element.isJsonObject()).isTrue();
JsonObject mapJsonObject = element.getAsJsonObject();
assertTrue(mapJsonObject.has(key));
assertThat(mapJsonObject.has(key)).isTrue();
}
}

View File

@ -16,8 +16,7 @@
package com.google.gson;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static com.google.common.truth.Truth.assertThat;
import com.google.gson.annotations.Expose;
import com.google.gson.internal.Excluder;
@ -33,44 +32,44 @@ public class ExposeAnnotationExclusionStrategyTest {
private Excluder excluder = Excluder.DEFAULT.excludeFieldsWithoutExposeAnnotation();
@Test
public void testNeverSkipClasses() throws Exception {
assertFalse(excluder.excludeClass(MockObject.class, true));
assertFalse(excluder.excludeClass(MockObject.class, false));
public void testNeverSkipClasses() {
assertThat(excluder.excludeClass(MockObject.class, true)).isFalse();
assertThat(excluder.excludeClass(MockObject.class, false)).isFalse();
}
@Test
public void testSkipNonAnnotatedFields() throws Exception {
Field f = createFieldAttributes("hiddenField");
assertTrue(excluder.excludeField(f, true));
assertTrue(excluder.excludeField(f, false));
assertThat(excluder.excludeField(f, true)).isTrue();
assertThat(excluder.excludeField(f, false)).isTrue();
}
@Test
public void testSkipExplicitlySkippedFields() throws Exception {
Field f = createFieldAttributes("explicitlyHiddenField");
assertTrue(excluder.excludeField(f, true));
assertTrue(excluder.excludeField(f, false));
assertThat(excluder.excludeField(f, true)).isTrue();
assertThat(excluder.excludeField(f, false)).isTrue();
}
@Test
public void testNeverSkipExposedAnnotatedFields() throws Exception {
Field f = createFieldAttributes("exposedField");
assertFalse(excluder.excludeField(f, true));
assertFalse(excluder.excludeField(f, false));
assertThat(excluder.excludeField(f, true)).isFalse();
assertThat(excluder.excludeField(f, false)).isFalse();
}
@Test
public void testNeverSkipExplicitlyExposedAnnotatedFields() throws Exception {
Field f = createFieldAttributes("explicitlyExposedField");
assertFalse(excluder.excludeField(f, true));
assertFalse(excluder.excludeField(f, false));
assertThat(excluder.excludeField(f, true)).isFalse();
assertThat(excluder.excludeField(f, false)).isFalse();
}
@Test
public void testDifferentSerializeAndDeserializeField() throws Exception {
Field f = createFieldAttributes("explicitlyDifferentModeField");
assertFalse(excluder.excludeField(f, true));
assertTrue(excluder.excludeField(f, false));
assertThat(excluder.excludeField(f, true)).isFalse();
assertThat(excluder.excludeField(f, false)).isTrue();
}
private static Field createFieldAttributes(String fieldName) throws Exception {

View File

@ -16,9 +16,7 @@
package com.google.gson;
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.reflect.TypeToken;
@ -44,7 +42,7 @@ public class FieldAttributesTest {
@SuppressWarnings("unused")
@Test
public void testNullField() throws Exception {
public void testNullField() {
try {
new FieldAttributes(null);
fail("Field parameter can not be null");
@ -52,32 +50,32 @@ public class FieldAttributesTest {
}
@Test
public void testDeclaringClass() throws Exception {
assertEquals(Foo.class, fieldAttributes.getDeclaringClass());
public void testDeclaringClass() {
assertThat(fieldAttributes.getDeclaringClass()).isAssignableTo(Foo.class);
}
@Test
public void testModifiers() throws Exception {
assertFalse(fieldAttributes.hasModifier(Modifier.STATIC));
assertFalse(fieldAttributes.hasModifier(Modifier.FINAL));
assertFalse(fieldAttributes.hasModifier(Modifier.ABSTRACT));
assertFalse(fieldAttributes.hasModifier(Modifier.VOLATILE));
assertFalse(fieldAttributes.hasModifier(Modifier.PROTECTED));
public void testModifiers() {
assertThat(fieldAttributes.hasModifier(Modifier.STATIC)).isFalse();
assertThat(fieldAttributes.hasModifier(Modifier.FINAL)).isFalse();
assertThat(fieldAttributes.hasModifier(Modifier.ABSTRACT)).isFalse();
assertThat(fieldAttributes.hasModifier(Modifier.VOLATILE)).isFalse();
assertThat(fieldAttributes.hasModifier(Modifier.PROTECTED)).isFalse();
assertTrue(fieldAttributes.hasModifier(Modifier.PUBLIC));
assertTrue(fieldAttributes.hasModifier(Modifier.TRANSIENT));
assertThat(fieldAttributes.hasModifier(Modifier.PUBLIC)).isTrue();
assertThat(fieldAttributes.hasModifier(Modifier.TRANSIENT)).isTrue();
}
@Test
public void testName() throws Exception {
assertEquals("bar", fieldAttributes.getName());
public void testName() {
assertThat(fieldAttributes.getName()).isEqualTo("bar");
}
@Test
public void testDeclaredTypeAndClass() throws Exception {
public void testDeclaredTypeAndClass() {
Type expectedType = new TypeToken<List<String>>() {}.getType();
assertEquals(expectedType, fieldAttributes.getDeclaredType());
assertEquals(List.class, fieldAttributes.getDeclaredClass());
assertThat(fieldAttributes.getDeclaredType()).isEqualTo(expectedType);
assertThat(fieldAttributes.getDeclaredClass()).isAssignableTo(List.class);
}
private static class Foo {

View File

@ -1,7 +1,8 @@
package com.google.gson;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage;
import java.lang.reflect.Field;
import java.util.Locale;
import org.junit.Test;
@ -28,7 +29,7 @@ public class FieldNamingPolicyTest {
};
for (String[] pair : argumentPairs) {
assertEquals(pair[1], FieldNamingPolicy.separateCamelCase(pair[0], '_'));
assertThat(FieldNamingPolicy.separateCamelCase(pair[0], '_')).isEqualTo(pair[1]);
}
}
@ -51,12 +52,12 @@ public class FieldNamingPolicyTest {
};
for (String[] pair : argumentPairs) {
assertEquals(pair[1], FieldNamingPolicy.upperCaseFirstLetter(pair[0]));
assertThat(FieldNamingPolicy.upperCaseFirstLetter(pair[0])).isEqualTo(pair[1]);
}
}
/**
* Upper casing policies should be unaffected by default Locale.
* Upper-casing policies should be unaffected by default Locale.
*/
@Test
public void testUpperCasingLocaleIndependent() throws Exception {
@ -81,11 +82,13 @@ public class FieldNamingPolicyTest {
try {
// Verify that default Locale has different case conversion rules
assertNotEquals("Test setup is broken", expected, name.toUpperCase());
assertWithMessage("Test setup is broken")
.that(name.toUpperCase()).doesNotMatch(expected);
for (FieldNamingPolicy policy : policies) {
// Should ignore default Locale
assertEquals("Unexpected conversion for " + policy, expected, policy.translateName(field));
assertWithMessage("Unexpected conversion for %s", policy)
.that(policy.translateName(field)).matches(expected);
}
} finally {
Locale.setDefault(oldLocale);
@ -118,11 +121,13 @@ public class FieldNamingPolicyTest {
try {
// Verify that default Locale has different case conversion rules
assertNotEquals("Test setup is broken", expected, name.toLowerCase());
assertWithMessage("Test setup is broken")
.that(name.toLowerCase()).doesNotMatch(expected);
for (FieldNamingPolicy policy : policies) {
// Should ignore default Locale
assertEquals("Unexpected conversion for " + policy, expected, policy.translateName(field));
assertWithMessage("Unexpected conversion for %s", policy)
.that(policy.translateName(field)).matches(expected);
}
} finally {
Locale.setDefault(oldLocale);

View File

@ -16,8 +16,7 @@
package com.google.gson;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static com.google.common.truth.Truth.assertThat;
import com.google.gson.internal.$Gson$Types;
import com.google.gson.reflect.TypeToken;
@ -46,15 +45,15 @@ public class GenericArrayTypeTest {
Type parameterizedType = new TypeToken<List<String>>() {}.getType();
Type genericArrayType = new TypeToken<List<String>[]>() {}.getType();
assertEquals(parameterizedType, ourType.getGenericComponentType());
assertEquals(genericArrayType, ourType);
assertEquals(genericArrayType.hashCode(), ourType.hashCode());
assertThat(ourType.getGenericComponentType()).isEqualTo(parameterizedType);
assertThat(ourType).isEqualTo(genericArrayType);
assertThat(ourType.hashCode()).isEqualTo(genericArrayType.hashCode());
}
@Test
public void testNotEquals() throws Exception {
Type differentGenericArrayType = new TypeToken<List<String>[][]>() {}.getType();
assertFalse(differentGenericArrayType.equals(ourType));
assertFalse(ourType.equals(differentGenericArrayType));
assertThat(differentGenericArrayType.equals(ourType)).isFalse();
assertThat(ourType.equals(differentGenericArrayType)).isFalse();
}
}

View File

@ -16,9 +16,7 @@
package com.google.gson;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.fail;
import com.google.gson.stream.JsonReader;
@ -48,8 +46,8 @@ public class GsonBuilderTest {
public void testCreatingMoreThanOnce() {
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
assertNotNull(gson);
assertNotNull(builder.create());
assertThat(gson).isNotNull();
assertThat(builder.create()).isNotNull();
builder.setFieldNamingStrategy(new FieldNamingStrategy() {
@Override public String translateName(Field f) {
@ -58,9 +56,9 @@ public class GsonBuilderTest {
});
Gson otherGson = builder.create();
assertNotNull(otherGson);
assertThat(otherGson).isNotNull();
// Should be different instances because builder has been modified in the meantime
assertNotSame(gson, otherGson);
assertThat(gson).isNotSameInstanceAs(otherGson);
}
/**
@ -74,7 +72,7 @@ public class GsonBuilderTest {
// Modifications of `gsonBuilder` should not affect `gson` object
gsonBuilder.registerTypeAdapter(CustomClass1.class, new TypeAdapter<CustomClass1>() {
@Override public CustomClass1 read(JsonReader in) throws IOException {
@Override public CustomClass1 read(JsonReader in) {
throw new UnsupportedOperationException();
}
@ -93,6 +91,7 @@ public class GsonBuilderTest {
}
});
assertDefaultGson(gson);
// New GsonBuilder created from `gson` should not have been affected by changes
// to `gsonBuilder` either
@ -105,26 +104,26 @@ public class GsonBuilderTest {
private static void assertDefaultGson(Gson gson) {
// Should use default reflective adapter
String json1 = gson.toJson(new CustomClass1());
assertEquals("{}", json1);
assertThat(json1).isEqualTo("{}");
// Should use default reflective adapter
String json2 = gson.toJson(new CustomClass2());
assertEquals("{}", json2);
assertThat(json2).isEqualTo("{}");
// Should use default instance creator
CustomClass3 customClass3 = gson.fromJson("{}", CustomClass3.class);
assertEquals(CustomClass3.NO_ARG_CONSTRUCTOR_VALUE, customClass3.s);
assertThat(customClass3.s).isEqualTo(CustomClass3.NO_ARG_CONSTRUCTOR_VALUE);
}
private static void assertCustomGson(Gson gson) {
String json1 = gson.toJson(new CustomClass1());
assertEquals("\"custom-adapter\"", json1);
assertThat(json1).isEqualTo("\"custom-adapter\"");
String json2 = gson.toJson(new CustomClass2());
assertEquals("\"custom-hierarchy-adapter\"", json2);
assertThat(json2).isEqualTo("\"custom-hierarchy-adapter\"");
CustomClass3 customClass3 = gson.fromJson("{}", CustomClass3.class);
assertEquals("custom-instance", customClass3.s);
assertThat(customClass3.s).isEqualTo("custom-instance");
}
static class CustomClass1 { }
@ -148,7 +147,7 @@ public class GsonBuilderTest {
Gson gson = new GsonBuilder()
.excludeFieldsWithModifiers(Modifier.VOLATILE, Modifier.PRIVATE)
.create();
assertEquals("{\"d\":\"d\"}", gson.toJson(new HasModifiers()));
assertThat(gson.toJson(new HasModifiers())).isEqualTo("{\"d\":\"d\"}");
}
@SuppressWarnings("unused")
@ -164,7 +163,7 @@ public class GsonBuilderTest {
Gson gson = new GsonBuilder()
.excludeFieldsWithModifiers()
.create();
assertEquals("{\"a\":\"a\"}", gson.toJson(new HasTransients()));
assertThat(gson.toJson(new HasTransients())).isEqualTo("{\"a\":\"a\"}");
}
static class HasTransients {
@ -195,12 +194,10 @@ public class GsonBuilderTest {
gson.fromJson("{}", ClassWithoutNoArgsConstructor.class);
fail("Expected exception");
} catch (JsonIOException expected) {
assertEquals(
"Unable to create instance of class com.google.gson.GsonBuilderTest$ClassWithoutNoArgsConstructor; "
+ "usage of JDK Unsafe is disabled. Registering an InstanceCreator or a TypeAdapter for this type, "
+ "adding a no-args constructor, or enabling usage of JDK Unsafe may fix this problem.",
expected.getMessage()
);
assertThat(expected).hasMessageThat().isEqualTo(
"Unable to create instance of class com.google.gson.GsonBuilderTest$ClassWithoutNoArgsConstructor; "
+ "usage of JDK Unsafe is disabled. Registering an InstanceCreator or a TypeAdapter for this type, "
+ "adding a no-args constructor, or enabling usage of JDK Unsafe may fix this problem.");
}
}
@ -217,14 +214,14 @@ public class GsonBuilderTest {
builder.setVersion(Double.NaN);
fail();
} catch (IllegalArgumentException e) {
assertEquals("Invalid version: NaN", e.getMessage());
assertThat(e).hasMessageThat().isEqualTo("Invalid version: NaN");
}
try {
builder.setVersion(-0.1);
fail();
} catch (IllegalArgumentException e) {
assertEquals("Invalid version: -0.1", e.getMessage());
assertThat(e).hasMessageThat().isEqualTo("Invalid version: -0.1");
}
}
}

View File

@ -16,8 +16,7 @@
package com.google.gson;
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.Gson.FutureTypeAdapter;
@ -70,10 +69,10 @@ public final class GsonTest {
CUSTOM_OBJECT_TO_NUMBER_STRATEGY, CUSTOM_NUMBER_TO_NUMBER_STRATEGY,
Collections.<ReflectionAccessFilter>emptyList());
assertEquals(CUSTOM_EXCLUDER, gson.excluder);
assertEquals(CUSTOM_FIELD_NAMING_STRATEGY, gson.fieldNamingStrategy());
assertEquals(true, gson.serializeNulls());
assertEquals(false, gson.htmlSafe());
assertThat(gson.excluder).isEqualTo(CUSTOM_EXCLUDER);
assertThat(gson.fieldNamingStrategy()).isEqualTo(CUSTOM_FIELD_NAMING_STRATEGY);
assertThat(gson.serializeNulls()).isTrue();
assertThat(gson.htmlSafe()).isFalse();
}
@Test
@ -90,14 +89,14 @@ public final class GsonTest {
.registerTypeAdapter(Object.class, new TestTypeAdapter())
.create();
assertEquals(original.factories.size() + 1, clone.factories.size());
assertThat(clone.factories).hasSize(original.factories.size() + 1);
}
private static final class TestTypeAdapter extends TypeAdapter<Object> {
@Override public void write(JsonWriter out, Object value) throws IOException {
@Override public void write(JsonWriter out, Object value) {
// Test stub.
}
@Override public Object read(JsonReader in) throws IOException { return null; }
@Override public Object read(JsonReader in) { return null; }
}
@Test
@ -107,7 +106,7 @@ public final class GsonTest {
gson.getAdapter((TypeToken<?>) null);
fail();
} catch (NullPointerException e) {
assertEquals("type must not be null", e.getMessage());
assertThat(e).hasMessageThat().isEqualTo("type must not be null");
}
}
@ -159,9 +158,9 @@ public final class GsonTest {
.create();
TypeAdapter<?> adapter = gson.getAdapter(requestedType);
assertEquals(2, adapterInstancesCreated.get());
assertTrue(adapter instanceof DummyAdapter);
assertTrue(threadAdapter.get() instanceof DummyAdapter);
assertThat(adapterInstancesCreated.get()).isEqualTo(2);
assertThat(adapter).isInstanceOf(DummyAdapter.class);
assertThat(threadAdapter.get()).isInstanceOf(DummyAdapter.class);
}
/**
@ -239,7 +238,7 @@ public final class GsonTest {
}
else if (raw == CustomClass2.class) {
TypeAdapter<?> adapter = gson.getAdapter(CustomClass1.class);
assertTrue(adapter instanceof FutureTypeAdapter);
assertThat(adapter).isInstanceOf(FutureTypeAdapter.class);
return new WrappingAdapter<>(adapter);
}
else {
@ -262,12 +261,12 @@ public final class GsonTest {
isThreadWaiting.await();
TypeAdapter<?> adapter = gson.getAdapter(CustomClass1.class);
// Should not fail due to referring to unresolved FutureTypeAdapter
assertEquals("[[\"wrapped-nested\"]]", adapter.toJson(null));
assertThat(adapter.toJson(null)).isEqualTo("[[\"wrapped-nested\"]]");
// Let other thread proceed and have it resolve its FutureTypeAdapter
canThreadProceed.countDown();
thread.join();
assertEquals("[[\"wrapped-nested\"]]", otherThreadAdapter.get().toJson(null));
assertThat(otherThreadAdapter.get().toJson(null)).isEqualTo("[[\"wrapped-nested\"]]");
}
@Test
@ -286,11 +285,11 @@ public final class GsonTest {
jsonWriter.value(1);
fail();
} catch (IllegalStateException expected) {
assertEquals("JSON must have only one top-level value.", expected.getMessage());
assertThat(expected).hasMessageThat().isEqualTo("JSON must have only one top-level value.");
}
jsonWriter.close();
assertEquals("{\"\\u003ctest2\":true}", writer.toString());
assertThat(writer.toString()).isEqualTo("{\"\\u003ctest2\":true}");
}
@Test
@ -315,7 +314,7 @@ public final class GsonTest {
jsonWriter.value(1);
jsonWriter.close();
assertEquals(")]}'\n{\n \"test\": null,\n \"<test2\": true\n}1", writer.toString());
assertThat(writer.toString()).isEqualTo(")]}'\n{\n \"test\": null,\n \"<test2\": true\n}1");
}
@Test
@ -337,7 +336,7 @@ public final class GsonTest {
.setLenient()
.create()
.newJsonReader(new StringReader(json));
assertEquals("test", jsonReader.nextString());
assertThat(jsonReader.nextString()).isEqualTo("test");
jsonReader.close();
}
@ -382,15 +381,15 @@ public final class GsonTest {
private static void assertDefaultGson(Gson gson) {
// Should use default reflective adapter
String json1 = gson.toJson(new CustomClass1());
assertEquals("{}", json1);
assertThat(json1).isEqualTo("{}");
// Should use default reflective adapter
String json2 = gson.toJson(new CustomClass2());
assertEquals("{}", json2);
assertThat(json2).isEqualTo("{}");
// Should use default instance creator
CustomClass3 customClass3 = gson.fromJson("{}", CustomClass3.class);
assertEquals(CustomClass3.NO_ARG_CONSTRUCTOR_VALUE, customClass3.s);
assertThat(customClass3.s).isEqualTo(CustomClass3.NO_ARG_CONSTRUCTOR_VALUE);
}
/**
@ -454,24 +453,24 @@ public final class GsonTest {
// But new Gson instance from `gsonBuilder` should be affected by changes
Gson otherGson = gsonBuilder.create();
String json1 = otherGson.toJson(new CustomClass1());
assertEquals("\"overwritten custom-adapter\"", json1);
assertThat(json1).isEqualTo("\"overwritten custom-adapter\"");
String json2 = otherGson.toJson(new CustomClass2());
assertEquals("\"overwritten custom-hierarchy-adapter\"", json2);
assertThat(json2).isEqualTo("\"overwritten custom-hierarchy-adapter\"");
CustomClass3 customClass3 = otherGson.fromJson("{}", CustomClass3.class);
assertEquals("overwritten custom-instance", customClass3.s);
assertThat(customClass3.s).isEqualTo("overwritten custom-instance");
}
private static void assertCustomGson(Gson gson) {
String json1 = gson.toJson(new CustomClass1());
assertEquals("\"custom-adapter\"", json1);
assertThat(json1).isEqualTo("\"custom-adapter\"");
String json2 = gson.toJson(new CustomClass2());
assertEquals("\"custom-hierarchy-adapter\"", json2);
assertThat(json2).isEqualTo("\"custom-hierarchy-adapter\"");
CustomClass3 customClass3 = gson.fromJson("{}", CustomClass3.class);
assertEquals("custom-instance", customClass3.s);
assertThat(customClass3.s).isEqualTo("custom-instance");
}
private static class CustomClass1 { }

View File

@ -16,8 +16,7 @@
package com.google.gson;
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.Type;
@ -60,7 +59,7 @@ public class GsonTypeAdapterTest {
} catch (IllegalStateException expected) { }
// Verify that serializer is made null-safe, i.e. it is not called for null
assertEquals("null", gson.toJson(null, AtomicLong.class));
assertThat(gson.toJson(null, AtomicLong.class)).isEqualTo("null");
try {
gson.fromJson("123", AtomicLong.class);
@ -68,28 +67,28 @@ public class GsonTypeAdapterTest {
} catch (JsonParseException expected) { }
// Verify that deserializer is made null-safe, i.e. it is not called for null
assertNull(gson.fromJson(JsonNull.INSTANCE, AtomicLong.class));
assertThat(gson.fromJson(JsonNull.INSTANCE, AtomicLong.class)).isNull();
}
@Test
public void testTypeAdapterProperlyConvertsTypes() throws Exception {
public void testTypeAdapterProperlyConvertsTypes() {
int intialValue = 1;
AtomicInteger atomicInt = new AtomicInteger(intialValue);
String json = gson.toJson(atomicInt);
assertEquals(intialValue + 1, Integer.parseInt(json));
assertThat(Integer.parseInt(json)).isEqualTo(intialValue + 1);
atomicInt = gson.fromJson(json, AtomicInteger.class);
assertEquals(intialValue, atomicInt.get());
assertThat(atomicInt.get()).isEqualTo(intialValue);
}
@Test
public void testTypeAdapterDoesNotAffectNonAdaptedTypes() throws Exception {
public void testTypeAdapterDoesNotAffectNonAdaptedTypes() {
String expected = "blah";
String actual = gson.toJson(expected);
assertEquals("\"" + expected + "\"", actual);
assertThat(actual).isEqualTo("\"" + expected + "\"");
actual = gson.fromJson(actual, String.class);
assertEquals(expected, actual);
assertThat(actual).isEqualTo(expected);
}
private static class ExceptionTypeAdapter
@ -158,6 +157,6 @@ public class GsonTypeAdapterTest {
builder.registerTypeHierarchyAdapter(Abstract.class, deserializer);
}
Gson gson = builder.create();
assertEquals(expected, gson.toJson(instance, instanceType));
assertThat(gson.toJson(instance, instanceType)).isEqualTo(expected);
}
}

View File

@ -16,8 +16,7 @@
package com.google.gson;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static com.google.common.truth.Truth.assertThat;
import com.google.gson.internal.Excluder;
import java.lang.reflect.Field;
@ -34,27 +33,27 @@ public class InnerClassExclusionStrategyTest {
private Excluder excluder = Excluder.DEFAULT.disableInnerClassSerialization();
@Test
public void testExcludeInnerClassObject() throws Exception {
public void testExcludeInnerClassObject() {
Class<?> clazz = innerClass.getClass();
assertTrue(excluder.excludeClass(clazz, true));
assertThat(excluder.excludeClass(clazz, true)).isTrue();
}
@Test
public void testExcludeInnerClassField() throws Exception {
Field f = getClass().getField("innerClass");
assertTrue(excluder.excludeField(f, true));
assertThat(excluder.excludeField(f, true)).isTrue();
}
@Test
public void testIncludeStaticNestedClassObject() throws Exception {
public void testIncludeStaticNestedClassObject() {
Class<?> clazz = staticNestedClass.getClass();
assertFalse(excluder.excludeClass(clazz, true));
assertThat(excluder.excludeClass(clazz, true)).isFalse();
}
@Test
public void testIncludeStaticNestedClassField() throws Exception {
Field f = getClass().getField("staticNestedClass");
assertFalse(excluder.excludeField(f, true));
assertThat(excluder.excludeField(f, true)).isFalse();
}
class InnerClass {

View File

@ -16,7 +16,7 @@
package com.google.gson;
import static org.junit.Assert.assertEquals;
import static com.google.common.truth.Truth.assertThat;
import com.google.gson.reflect.TypeToken;
import java.io.ByteArrayInputStream;
@ -25,8 +25,6 @@ import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import org.junit.Test;
@ -44,9 +42,9 @@ public final class JavaSerializationTest {
Type type = new TypeToken<Map<String, Integer>>() {}.getType();
Map<String, Integer> map = gson.fromJson("{\"b\":1,\"c\":2,\"a\":3}", type);
Map<String, Integer> serialized = serializedCopy(map);
assertEquals(map, serialized);
assertThat(serialized).isEqualTo(map);
// Also check that the iteration order is retained.
assertEquals(Arrays.asList("b", "c", "a"), new ArrayList<>(serialized.keySet()));
assertThat(serialized.keySet()).containsExactly("b", "c", "a").inOrder();
}
@Test
@ -54,7 +52,7 @@ public final class JavaSerializationTest {
Type type = new TypeToken<List<String>>() {}.getType();
List<String> list = gson.fromJson("[\"a\",\"b\",\"c\"]", type);
List<String> serialized = serializedCopy(list);
assertEquals(list, serialized);
assertThat(serialized).isEqualTo(list);
}
@Test
@ -62,9 +60,9 @@ public final class JavaSerializationTest {
Type type = new TypeToken<List<Number>>() {}.getType();
List<Number> list = gson.fromJson("[1,3.14,6.673e-11]", type);
List<Number> serialized = serializedCopy(list);
assertEquals(1.0, serialized.get(0).doubleValue(), 0);
assertEquals(3.14, serialized.get(1).doubleValue(), 0);
assertEquals(6.673e-11, serialized.get(2).doubleValue(), 0);
assertThat(serialized.get(0).doubleValue()).isEqualTo(1.0);
assertThat(serialized.get(1).doubleValue()).isEqualTo(3.14);
assertThat(serialized.get(2).doubleValue()).isEqualTo(6.673e-11);
}
@SuppressWarnings("unchecked") // Serialization promises to return the same type.

View File

@ -1,10 +1,6 @@
package com.google.gson;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
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.common.MoreAsserts;
@ -23,7 +19,7 @@ public class JsonArrayAsListTest {
a.add(1);
List<JsonElement> list = a.asList();
assertEquals(new JsonPrimitive(1), list.get(0));
assertThat(list.get(0)).isEqualTo(new JsonPrimitive(1));
try {
list.get(-1);
@ -38,7 +34,7 @@ public class JsonArrayAsListTest {
}
a.add((JsonElement) null);
assertEquals(JsonNull.INSTANCE, list.get(1));
assertThat(list.get(1)).isEqualTo(JsonNull.INSTANCE);
}
@Test
@ -47,9 +43,9 @@ public class JsonArrayAsListTest {
a.add(1);
List<JsonElement> list = a.asList();
assertEquals(1, list.size());
assertThat(list).hasSize(1);
list.add(new JsonPrimitive(2));
assertEquals(2, list.size());
assertThat(list).hasSize(2);
}
@Test
@ -59,9 +55,9 @@ public class JsonArrayAsListTest {
List<JsonElement> list = a.asList();
JsonElement old = list.set(0, new JsonPrimitive(2));
assertEquals(new JsonPrimitive(1), old);
assertEquals(new JsonPrimitive(2), list.get(0));
assertEquals(new JsonPrimitive(2), a.get(0));
assertThat(old).isEqualTo(new JsonPrimitive(1));
assertThat(list.get(0)).isEqualTo(new JsonPrimitive(2));
assertThat(a.get(0)).isEqualTo(new JsonPrimitive(2));
try {
list.set(-1, new JsonPrimitive(1));
@ -79,7 +75,7 @@ public class JsonArrayAsListTest {
list.set(0, null);
fail();
} catch (NullPointerException e) {
assertEquals("Element must be non-null", e.getMessage());
assertThat(e).hasMessageThat().isEqualTo("Element must be non-null");
}
}
@ -91,8 +87,8 @@ public class JsonArrayAsListTest {
List<JsonElement> list = a.asList();
list.add(0, new JsonPrimitive(2));
list.add(1, new JsonPrimitive(3));
assertTrue(list.add(new JsonPrimitive(4)));
assertTrue(list.add(JsonNull.INSTANCE));
assertThat(list.add(new JsonPrimitive(4))).isTrue();
assertThat(list.add(JsonNull.INSTANCE)).isTrue();
List<JsonElement> expectedList = Arrays.<JsonElement>asList(
new JsonPrimitive(2),
@ -101,7 +97,7 @@ public class JsonArrayAsListTest {
new JsonPrimitive(4),
JsonNull.INSTANCE
);
assertEquals(expectedList, list);
assertThat(list).isEqualTo(expectedList);
try {
list.set(-1, new JsonPrimitive(1));
@ -119,13 +115,13 @@ public class JsonArrayAsListTest {
list.add(0, null);
fail();
} catch (NullPointerException e) {
assertEquals("Element must be non-null", e.getMessage());
assertThat(e).hasMessageThat().isEqualTo("Element must be non-null");
}
try {
list.add(null);
fail();
} catch (NullPointerException e) {
assertEquals("Element must be non-null", e.getMessage());
assertThat(e).hasMessageThat().isEqualTo("Element must be non-null");
}
}
@ -142,19 +138,20 @@ public class JsonArrayAsListTest {
new JsonPrimitive(2),
new JsonPrimitive(3)
);
assertEquals(expectedList, list);
assertThat(list).isEqualTo(expectedList);
assertThat(list).isEqualTo(expectedList);
try {
list.addAll(0, Collections.<JsonElement>singletonList(null));
fail();
} catch (NullPointerException e) {
assertEquals("Element must be non-null", e.getMessage());
assertThat(e).hasMessageThat().isEqualTo("Element must be non-null");
}
try {
list.addAll(Collections.<JsonElement>singletonList(null));
fail();
} catch (NullPointerException e) {
assertEquals("Element must be non-null", e.getMessage());
assertThat(e).hasMessageThat().isEqualTo("Element must be non-null");
}
}
@ -164,10 +161,9 @@ public class JsonArrayAsListTest {
a.add(1);
List<JsonElement> list = a.asList();
assertEquals(new JsonPrimitive(1), list.remove(0));
assertEquals(0, list.size());
assertEquals(0, a.size());
assertThat(list.remove(0)).isEqualTo(new JsonPrimitive(1));
assertThat(list).hasSize(0);
assertThat(a).hasSize(0);
try {
list.remove(0);
fail();
@ -181,12 +177,12 @@ public class JsonArrayAsListTest {
a.add(1);
List<JsonElement> list = a.asList();
assertTrue(list.remove(new JsonPrimitive(1)));
assertEquals(0, list.size());
assertEquals(0, a.size());
assertThat(list.remove(new JsonPrimitive(1))).isTrue();
assertThat(list).hasSize(0);
assertThat(a).hasSize(0);
assertFalse(list.remove(new JsonPrimitive(1)));
assertFalse(list.remove(null));
assertThat(list.remove(new JsonPrimitive(1))).isFalse();
assertThat(list.remove(null)).isFalse();
}
@Test
@ -196,8 +192,8 @@ public class JsonArrayAsListTest {
List<JsonElement> list = a.asList();
list.clear();
assertEquals(0, list.size());
assertEquals(0, a.size());
assertThat(list).hasSize(0);
assertThat(a).hasSize(0);
}
@Test
@ -206,13 +202,13 @@ public class JsonArrayAsListTest {
a.add(1);
List<JsonElement> list = a.asList();
assertTrue(list.contains(new JsonPrimitive(1)));
assertFalse(list.contains(new JsonPrimitive(2)));
assertFalse(list.contains(null));
assertThat(list.contains(new JsonPrimitive(1))).isTrue();
assertThat(list.contains(new JsonPrimitive(2))).isFalse();
assertThat(list.contains(null)).isFalse();
@SuppressWarnings({"unlikely-arg-type", "CollectionIncompatibleType"})
boolean containsInt = list.contains(1); // should only contain JsonPrimitive(1)
assertFalse(containsInt);
assertThat(containsInt).isFalse();
}
@Test
@ -223,17 +219,17 @@ public class JsonArrayAsListTest {
a.add(1);
List<JsonElement> list = a.asList();
assertEquals(0, list.indexOf(new JsonPrimitive(1)));
assertEquals(-1, list.indexOf(new JsonPrimitive(2)));
assertEquals(-1, list.indexOf(null));
assertThat(list.indexOf(new JsonPrimitive(1))).isEqualTo(0);
assertThat(list.indexOf(new JsonPrimitive(2))).isEqualTo(-1);
assertThat(list.indexOf(null)).isEqualTo(-1);
@SuppressWarnings({"unlikely-arg-type", "CollectionIncompatibleType"})
int indexOfInt = list.indexOf(1); // should only contain JsonPrimitive(1)
assertEquals(-1, indexOfInt);
assertThat(indexOfInt).isEqualTo(-1);
assertEquals(1, list.lastIndexOf(new JsonPrimitive(1)));
assertEquals(-1, list.lastIndexOf(new JsonPrimitive(2)));
assertEquals(-1, list.lastIndexOf(null));
assertThat(list.lastIndexOf(new JsonPrimitive(1))).isEqualTo(1);
assertThat(list.lastIndexOf(new JsonPrimitive(2))).isEqualTo(-1);
assertThat(list.lastIndexOf(null)).isEqualTo(-1);
}
@Test
@ -242,19 +238,19 @@ public class JsonArrayAsListTest {
a.add(1);
List<JsonElement> list = a.asList();
assertArrayEquals(new Object[] {new JsonPrimitive(1)}, list.toArray());
assertThat(list.toArray()).isEqualTo(new Object[] {new JsonPrimitive(1)});
JsonElement[] array = list.toArray(new JsonElement[0]);
assertArrayEquals(new Object[] {new JsonPrimitive(1)}, array);
assertThat(array).isEqualTo(new Object[] {new JsonPrimitive(1)});
array = new JsonElement[1];
assertSame(array, list.toArray(array));
assertArrayEquals(new Object[] {new JsonPrimitive(1)}, array);
assertThat(list.toArray(array)).isEqualTo(array);
assertThat(array).isEqualTo(new Object[] {new JsonPrimitive(1)});
array = new JsonElement[] {null, new JsonPrimitive(2)};
assertSame(array, list.toArray(array));
assertThat(list.toArray(array)).isEqualTo(array);
// Should have set existing array element to null
assertArrayEquals(new Object[] {new JsonPrimitive(1), null}, array);
assertThat(array).isEqualTo(new Object[] {new JsonPrimitive(1), null});
}
@Test
@ -264,8 +260,8 @@ public class JsonArrayAsListTest {
List<JsonElement> list = a.asList();
MoreAsserts.assertEqualsAndHashCode(list, Collections.singletonList(new JsonPrimitive(1)));
assertFalse(list.equals(Collections.emptyList()));
assertFalse(list.equals(Collections.singletonList(new JsonPrimitive(2))));
assertThat(list.equals(Collections.emptyList())).isFalse();
assertThat(list.equals(Collections.singletonList(new JsonPrimitive(2)))).isFalse();
}
/** Verify that {@code JsonArray} updates are visible to view and vice versa */
@ -275,11 +271,11 @@ public class JsonArrayAsListTest {
List<JsonElement> list = a.asList();
a.add(1);
assertEquals(1, list.size());
assertEquals(new JsonPrimitive(1), list.get(0));
assertThat(list).hasSize(1);
assertThat(list.get(0)).isEqualTo(new JsonPrimitive(1));
list.add(new JsonPrimitive(2));
assertEquals(2, a.size());
assertEquals(new JsonPrimitive(2), a.get(1));
assertThat(a).hasSize(2);
assertThat(a.get(1)).isEqualTo(new JsonPrimitive(2));
}
}

View File

@ -16,9 +16,8 @@
package com.google.gson;
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 com.google.common.truth.Truth.assertWithMessage;
import static org.junit.Assert.fail;
import com.google.gson.common.MoreAsserts;
@ -40,22 +39,22 @@ public final class JsonArrayTest {
JsonArray a = new JsonArray();
JsonArray b = new JsonArray();
assertEquals(a, a);
assertThat(a).isEqualTo(a);
a.add(new JsonObject());
assertFalse(a.equals(b));
assertFalse(b.equals(a));
assertThat(a.equals(b)).isFalse();
assertThat(b.equals(a)).isFalse();
b.add(new JsonObject());
MoreAsserts.assertEqualsAndHashCode(a, b);
a.add(new JsonObject());
assertFalse(a.equals(b));
assertFalse(b.equals(a));
assertThat(a.equals(b)).isFalse();
assertThat(b.equals(a)).isFalse();
b.add(JsonNull.INSTANCE);
assertFalse(a.equals(b));
assertFalse(b.equals(a));
assertThat(a.equals(b)).isFalse();
assertThat(b.equals(a)).isFalse();
}
@Test
@ -67,13 +66,13 @@ public final class JsonArrayTest {
} catch (IndexOutOfBoundsException expected) {}
JsonPrimitive a = new JsonPrimitive("a");
array.add(a);
assertTrue(array.remove(a));
assertFalse(array.contains(a));
assertThat(array.remove(a)).isTrue();
assertThat(array.contains(a)).isFalse();
array.add(a);
array.add(new JsonPrimitive("b"));
assertEquals("b", array.remove(1).getAsString());
assertEquals(1, array.size());
assertTrue(array.contains(a));
assertThat(array.remove(1).getAsString()).isEqualTo("b");
assertThat(array).hasSize(1);
assertThat(array.contains(a)).isTrue();
}
@Test
@ -88,17 +87,17 @@ public final class JsonArrayTest {
JsonPrimitive b = new JsonPrimitive("b");
JsonElement oldValue = array.set(0, b);
assertEquals(a, oldValue);
assertEquals("b", array.get(0).getAsString());
assertThat(oldValue).isEqualTo(a);
assertThat(array.get(0).getAsString()).isEqualTo("b");
oldValue = array.set(0, null);
assertEquals(b, oldValue);
assertEquals(JsonNull.INSTANCE, array.get(0));
assertThat(oldValue).isEqualTo(b);
assertThat(array.get(0)).isEqualTo(JsonNull.INSTANCE);
oldValue = array.set(0, new JsonPrimitive("c"));
assertEquals(JsonNull.INSTANCE, oldValue);
assertEquals("c", array.get(0).getAsString());
assertEquals(1, array.size());
assertThat(oldValue).isEqualTo(JsonNull.INSTANCE);
assertThat(array.get(0).getAsString()).isEqualTo("c");
assertThat(array).hasSize(1);
}
@Test
@ -110,24 +109,24 @@ public final class JsonArrayTest {
JsonArray copy = original.deepCopy();
original.add(new JsonPrimitive("y"));
assertEquals(1, copy.size());
assertThat(copy).hasSize(1);
firstEntry.add(new JsonPrimitive("z"));
assertEquals(1, original.get(0).getAsJsonArray().size());
assertEquals(0, copy.get(0).getAsJsonArray().size());
assertThat(original.get(0).getAsJsonArray()).hasSize(1);
assertThat(copy.get(0).getAsJsonArray()).hasSize(0);
}
@Test
public void testIsEmpty() {
JsonArray array = new JsonArray();
assertTrue(array.isEmpty());
assertThat(array).isEmpty();
JsonPrimitive a = new JsonPrimitive("a");
array.add(a);
assertFalse(array.isEmpty());
assertThat(array).isNotEmpty();
array.remove(0);
assertTrue(array.isEmpty());
assertThat(array).isEmpty();
}
@Test
@ -138,22 +137,22 @@ public final class JsonArrayTest {
jsonArray.getAsBoolean();
fail("expected getBoolean to fail");
} catch (UnsupportedOperationException e) {
assertEquals("Expected an exception message",
"JsonObject", e.getMessage());
assertWithMessage("Expected an exception message")
.that(e).hasMessageThat().isEqualTo("JsonObject");
}
try {
jsonArray.get(-1);
fail("expected get to fail");
} catch (IndexOutOfBoundsException e) {
assertEquals("Expected an exception message",
"Index -1 out of bounds for length 1", e.getMessage());
assertWithMessage("Expected an exception message")
.that(e).hasMessageThat().isEqualTo("Index -1 out of bounds for length 1");
}
try {
jsonArray.getAsString();
fail("expected getString to fail");
} catch (UnsupportedOperationException e) {
assertEquals("Expected an exception message",
"JsonObject", e.getMessage());
assertWithMessage("Expected an exception message")
.that(e).hasMessageThat().isEqualTo("JsonObject");
}
jsonArray.remove(0);
@ -162,36 +161,36 @@ public final class JsonArrayTest {
jsonArray.getAsDouble();
fail("expected getDouble to fail");
} catch (NumberFormatException e) {
assertEquals("Expected an exception message",
"For input string: \"hello\"", e.getMessage());
assertWithMessage("Expected an exception message")
.that(e).hasMessageThat().isEqualTo("For input string: \"hello\"");
}
try {
jsonArray.getAsInt();
fail("expected getInt to fail");
} catch (NumberFormatException e) {
assertEquals("Expected an exception message",
"For input string: \"hello\"", e.getMessage());
assertWithMessage("Expected an exception message")
.that(e).hasMessageThat().isEqualTo("For input string: \"hello\"");
}
try {
jsonArray.get(0).getAsJsonArray();
fail("expected getJSONArray to fail");
} catch (IllegalStateException e) {
assertEquals("Expected an exception message",
"Not a JSON Array: \"hello\"", e.getMessage());
assertWithMessage("Expected an exception message")
.that(e).hasMessageThat().isEqualTo("Not a JSON Array: \"hello\"");
}
try {
jsonArray.getAsJsonObject();
fail("expected getJSONObject to fail");
} catch (IllegalStateException e) {
assertEquals("Expected an exception message",
"Not a JSON Object: [\"hello\"]", e.getMessage());
assertWithMessage("Expected an exception message")
.that(e).hasMessageThat().isEqualTo( "Not a JSON Object: [\"hello\"]");
}
try {
jsonArray.getAsLong();
fail("expected getLong to fail");
} catch (NumberFormatException e) {
assertEquals("Expected an exception message",
"For input string: \"hello\"", e.getMessage());
assertWithMessage("Expected an exception message")
.that(e).hasMessageThat().isEqualTo("For input string: \"hello\"");
}
}
@ -202,7 +201,7 @@ public final class JsonArrayTest {
jsonArray.getAsByte();
fail();
} catch (IllegalStateException e) {
assertEquals("Array must have size 1, but has size 0", e.getMessage());
assertThat(e).hasMessageThat().isEqualTo("Array must have size 1, but has size 0");
}
jsonArray.add(true);
@ -211,7 +210,7 @@ public final class JsonArrayTest {
jsonArray.getAsByte();
fail();
} catch (IllegalStateException e) {
assertEquals("Array must have size 1, but has size 2", e.getMessage());
assertThat(e).hasMessageThat().isEqualTo("Array must have size 1, but has size 2");
}
}
@ -225,7 +224,7 @@ public final class JsonArrayTest {
jsonArray.add((String) null);
jsonArray.add("Yes");
assertEquals("[\"Hello\",\"Goodbye\",\"Thank you\",null,\"Yes\"]", jsonArray.toString());
assertThat(jsonArray.toString()).isEqualTo("[\"Hello\",\"Goodbye\",\"Thank you\",null,\"Yes\"]");
}
@Test
@ -249,7 +248,7 @@ public final class JsonArrayTest {
x = 0;
jsonArray.add(x);
assertEquals("[1,2,-3,null,4,0]", jsonArray.toString());
assertThat(jsonArray.toString()).isEqualTo("[1,2,-3,null,4,0]");
}
@Test
@ -272,7 +271,7 @@ public final class JsonArrayTest {
jsonArray.add((Double) null);
assertEquals("[1.0,2.13232,0.121,null,-0.00234,null]", jsonArray.toString());
assertThat(jsonArray.toString()).isEqualTo("[1.0,2.13232,0.121,null,-0.00234,null]");
}
@Test
@ -286,7 +285,7 @@ public final class JsonArrayTest {
jsonArray.add((Boolean) null);
jsonArray.add(true);
assertEquals("[true,true,false,false,null,true]", jsonArray.toString());
assertThat(jsonArray.toString()).isEqualTo("[true,true,false,false,null,true]");
}
@Test
@ -301,7 +300,7 @@ public final class JsonArrayTest {
jsonArray.add('u');
jsonArray.add("and sometimes Y");
assertEquals("[\"a\",\"e\",\"i\",\"o\",null,\"u\",\"and sometimes Y\"]", jsonArray.toString());
assertThat(jsonArray.toString()).isEqualTo("[\"a\",\"e\",\"i\",\"o\",null,\"u\",\"and sometimes Y\"]");
}
@Test
@ -314,15 +313,15 @@ public final class JsonArrayTest {
jsonArray.add((char) 111);
jsonArray.add((Boolean) null);
assertEquals(JsonNull.INSTANCE, jsonArray.get(jsonArray.size() - 1));
assertThat(jsonArray.get(jsonArray.size() - 1)).isEqualTo(JsonNull.INSTANCE);
jsonArray.add((Character) null);
assertEquals(JsonNull.INSTANCE, jsonArray.get(jsonArray.size() - 1));
assertThat(jsonArray.get(jsonArray.size() - 1)).isEqualTo(JsonNull.INSTANCE);
jsonArray.add(12.232);
jsonArray.add(BigInteger.valueOf(2323));
assertEquals("[\"a\",\"apple\",12121,\"o\",null,null,12.232,2323]", jsonArray.toString());
assertThat(jsonArray.toString()).isEqualTo("[\"a\",\"apple\",12121,\"o\",null,null,12.232,2323]");
}
@Test
@ -339,10 +338,10 @@ public final class JsonArrayTest {
jsonArray.add((Boolean) null);
jsonArray.add((Number) null);
assertEquals("[null,null,null,null,null,null,null,null,null]", jsonArray.toString());
assertThat(jsonArray.toString()).isEqualTo("[null,null,null,null,null,null,null,null,null]");
for (int i = 0; i < jsonArray.size(); i++) {
// Verify that they are actually a JsonNull and not a Java null
assertEquals(JsonNull.INSTANCE, jsonArray.get(i));
assertThat(jsonArray.get(i)).isEqualTo(JsonNull.INSTANCE);
}
}
@ -350,7 +349,7 @@ public final class JsonArrayTest {
public void testNullJsonElementAddition() {
JsonArray jsonArray = new JsonArray();
jsonArray.add((JsonElement) null);
assertEquals(JsonNull.INSTANCE, jsonArray.get(0));
assertThat(jsonArray.get(0)).isEqualTo(JsonNull.INSTANCE);
}
@Test
@ -368,6 +367,6 @@ public final class JsonArrayTest {
jsonArray.add((Boolean) null);
jsonArray.add((Boolean) null);
assertEquals("[\"a\",\"a\",true,true,1212,1212,34.34,34.34,null,null]", jsonArray.toString());
assertThat(jsonArray.toString()).isEqualTo("[\"a\",\"a\",true,true,1212,1212,34.34,34.34,null,null]");
}
}

View File

@ -16,7 +16,7 @@
package com.google.gson;
import static org.junit.Assert.assertSame;
import static com.google.common.truth.Truth.assertThat;
import com.google.gson.common.MoreAsserts;
import org.junit.Test;
@ -38,7 +38,7 @@ public final class JsonNullTest {
public void testDeepCopy() {
@SuppressWarnings("deprecation")
JsonNull a = new JsonNull();
assertSame(JsonNull.INSTANCE, a.deepCopy());
assertSame(JsonNull.INSTANCE, JsonNull.INSTANCE.deepCopy());
assertThat(a.deepCopy()).isSameInstanceAs(JsonNull.INSTANCE);
assertThat(JsonNull.INSTANCE.deepCopy()).isSameInstanceAs(JsonNull.INSTANCE);
}
}

View File

@ -1,9 +1,6 @@
package com.google.gson;
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;
@ -26,15 +23,15 @@ public class JsonObjectAsMapTest {
@Test
public void testSize() {
JsonObject o = new JsonObject();
assertEquals(0, o.asMap().size());
assertThat(o.asMap().size()).isEqualTo(0);
o.addProperty("a", 1);
Map<String, JsonElement> map = o.asMap();
assertEquals(1, map.size());
assertThat(map).hasSize(1);
map.clear();
assertEquals(0, map.size());
assertEquals(0, o.size());
assertThat(map).hasSize(0);
assertThat(o.size()).isEqualTo(0);
}
@Test
@ -43,9 +40,9 @@ public class JsonObjectAsMapTest {
o.addProperty("a", 1);
Map<String, JsonElement> map = o.asMap();
assertTrue(map.containsKey("a"));
assertFalse(map.containsKey("b"));
assertFalse(map.containsKey(null));
assertThat(map.containsKey("a")).isTrue();
assertThat(map.containsKey("b")).isFalse();
assertThat(map.containsKey(null)).isFalse();
}
@Test
@ -55,13 +52,13 @@ public class JsonObjectAsMapTest {
o.add("b", JsonNull.INSTANCE);
Map<String, JsonElement> map = o.asMap();
assertTrue(map.containsValue(new JsonPrimitive(1)));
assertFalse(map.containsValue(new JsonPrimitive(2)));
assertFalse(map.containsValue(null));
assertThat(map.containsValue(new JsonPrimitive(1))).isTrue();
assertThat(map.containsValue(new JsonPrimitive(2))).isFalse();
assertThat(map.containsValue(null)).isFalse();
@SuppressWarnings({"unlikely-arg-type", "CollectionIncompatibleType"})
boolean containsInt = map.containsValue(1); // should only contain JsonPrimitive(1)
assertFalse(containsInt);
assertThat(containsInt).isFalse();
}
@Test
@ -70,9 +67,9 @@ public class JsonObjectAsMapTest {
o.addProperty("a", 1);
Map<String, JsonElement> map = o.asMap();
assertEquals(new JsonPrimitive(1), map.get("a"));
assertNull(map.get("b"));
assertNull(map.get(null));
assertThat(map.get("a")).isEqualTo(new JsonPrimitive(1));
assertThat(map.get("b")).isNull();
assertThat(map.get(null)).isNull();
}
@Test
@ -80,31 +77,30 @@ public class JsonObjectAsMapTest {
JsonObject o = new JsonObject();
Map<String, JsonElement> map = o.asMap();
assertNull(map.put("a", new JsonPrimitive(1)));
assertEquals(1, map.size());
assertEquals(new JsonPrimitive(1), map.get("a"));
assertThat(map.put("a", new JsonPrimitive(1))).isNull();
assertThat(map.get("a")).isEqualTo(new JsonPrimitive(1));
JsonElement old = map.put("a", new JsonPrimitive(2));
assertEquals(new JsonPrimitive(1), old);
assertEquals(1, map.size());
assertEquals(new JsonPrimitive(2), map.get("a"));
assertEquals(new JsonPrimitive(2), o.get("a"));
assertThat(old).isEqualTo(new JsonPrimitive(1));
assertThat(map).hasSize(1);
assertThat(map.get("a")).isEqualTo(new JsonPrimitive(2));
assertThat(o.get("a")).isEqualTo(new JsonPrimitive(2));
assertNull(map.put("b", JsonNull.INSTANCE));
assertEquals(JsonNull.INSTANCE, map.get("b"));
assertThat(map.put("b", JsonNull.INSTANCE)).isNull();
assertThat(map.get("b")).isEqualTo(JsonNull.INSTANCE);
try {
map.put(null, new JsonPrimitive(1));
fail();
} catch (NullPointerException e) {
assertEquals("key == null", e.getMessage());
assertThat(e).hasMessageThat().isEqualTo("key == null");
}
try {
map.put("a", null);
fail();
} catch (NullPointerException e) {
assertEquals("value == null", e.getMessage());
assertThat(e).hasMessageThat().isEqualTo("value == null");
}
}
@ -114,18 +110,18 @@ public class JsonObjectAsMapTest {
o.addProperty("a", 1);
Map<String, JsonElement> map = o.asMap();
assertNull(map.remove("b"));
assertEquals(1, map.size());
assertThat(map.remove("b")).isNull();
assertThat(map).hasSize(1);
JsonElement old = map.remove("a");
assertEquals(new JsonPrimitive(1), old);
assertEquals(0, map.size());
assertThat(old).isEqualTo(new JsonPrimitive(1));
assertThat(map).hasSize(0);
assertNull(map.remove("a"));
assertEquals(0, map.size());
assertEquals(0, o.size());
assertThat(map.remove("a")).isNull();
assertThat(map).hasSize(0);
assertThat(o.size()).isEqualTo(0);
assertNull(map.remove(null));
assertThat(map.remove(null)).isNull();
}
@Test
@ -139,22 +135,22 @@ public class JsonObjectAsMapTest {
Map<String, JsonElement> map = o.asMap();
map.putAll(otherMap);
assertEquals(2, map.size());
assertEquals(new JsonPrimitive(2), map.get("a"));
assertEquals(new JsonPrimitive(3), map.get("b"));
assertThat(map).hasSize(2);
assertThat(map.get("a")).isEqualTo(new JsonPrimitive(2));
assertThat(map.get("b")).isEqualTo(new JsonPrimitive(3));
try {
map.putAll(Collections.<String, JsonElement>singletonMap(null, new JsonPrimitive(1)));
fail();
} catch (NullPointerException e) {
assertEquals("key == null", e.getMessage());
assertThat(e).hasMessageThat().isEqualTo("key == null");
}
try {
map.putAll(Collections.<String, JsonElement>singletonMap("a", null));
fail();
} catch (NullPointerException e) {
assertEquals("value == null", e.getMessage());
assertThat(e).hasMessageThat().isEqualTo("value == null");
}
}
@ -165,8 +161,8 @@ public class JsonObjectAsMapTest {
Map<String, JsonElement> map = o.asMap();
map.clear();
assertEquals(0, map.size());
assertEquals(0, o.size());
assertThat(map).hasSize(0);
assertThat(o.size()).isEqualTo(0);
}
@Test
@ -178,7 +174,7 @@ public class JsonObjectAsMapTest {
Map<String, JsonElement> map = o.asMap();
Set<String> keySet = map.keySet();
// Should contain keys in same order
assertEquals(Arrays.asList("b", "a"), new ArrayList<>(keySet));
assertThat(keySet).containsExactly("b", "a").inOrder();
// Key set doesn't support insertions
try {
@ -187,9 +183,9 @@ public class JsonObjectAsMapTest {
} catch (UnsupportedOperationException e) {
}
assertTrue(keySet.remove("a"));
assertEquals(Collections.singleton("b"), map.keySet());
assertEquals(Collections.singleton("b"), o.keySet());
assertThat(keySet.remove("a")).isTrue();
assertThat(map.keySet()).isEqualTo(Collections.singleton("b"));
assertThat(o.keySet()).isEqualTo(Collections.singleton("b"));
}
@Test
@ -201,7 +197,7 @@ public class JsonObjectAsMapTest {
Map<String, JsonElement> map = o.asMap();
Collection<JsonElement> values = map.values();
// Should contain values in same order
assertEquals(Arrays.asList(new JsonPrimitive(2), new JsonPrimitive(1)), new ArrayList<>(values));
assertThat(values).containsExactly(new JsonPrimitive(2), new JsonPrimitive(1)).inOrder();
// Values collection doesn't support insertions
try {
@ -210,10 +206,10 @@ public class JsonObjectAsMapTest {
} catch (UnsupportedOperationException e) {
}
assertTrue(values.remove(new JsonPrimitive(2)));
assertEquals(Collections.singletonList(new JsonPrimitive(1)), new ArrayList<>(map.values()));
assertEquals(1, o.size());
assertEquals(new JsonPrimitive(1), o.get("b"));
assertThat(values.remove(new JsonPrimitive(2))).isTrue();
assertThat(new ArrayList<>(map.values())).isEqualTo(Collections.singletonList(new JsonPrimitive(1)));
assertThat(o.size()).isEqualTo(1);
assertThat(o.get("b")).isEqualTo(new JsonPrimitive(1));
}
@Test
@ -230,7 +226,7 @@ public class JsonObjectAsMapTest {
new SimpleEntry<>("a", new JsonPrimitive(1))
);
// Should contain entries in same order
assertEquals(expectedEntrySet, new ArrayList<>(entrySet));
assertThat(new ArrayList<>(entrySet)).isEqualTo(expectedEntrySet);
try {
entrySet.add(new SimpleEntry<String, JsonElement>("c", new JsonPrimitive(3)));
@ -238,24 +234,24 @@ public class JsonObjectAsMapTest {
} catch (UnsupportedOperationException e) {
}
assertTrue(entrySet.remove(new SimpleEntry<>("a", new JsonPrimitive(1))));
assertEquals(Collections.singleton(new SimpleEntry<>("b", new JsonPrimitive(2))), map.entrySet());
assertEquals(Collections.singleton(new SimpleEntry<>("b", new JsonPrimitive(2))), o.entrySet());
assertThat(entrySet.remove(new SimpleEntry<>("a", new JsonPrimitive(1)))).isTrue();
assertThat(map.entrySet()).isEqualTo(Collections.singleton(new SimpleEntry<>("b", new JsonPrimitive(2))));
assertThat(o.entrySet()).isEqualTo(Collections.singleton(new SimpleEntry<>("b", new JsonPrimitive(2))));
// Should return false because entry has already been removed
assertFalse(entrySet.remove(new SimpleEntry<>("a", new JsonPrimitive(1))));
assertThat(entrySet.remove(new SimpleEntry<>("a", new JsonPrimitive(1)))).isFalse();
Entry<String, JsonElement> entry = entrySet.iterator().next();
JsonElement old = entry.setValue(new JsonPrimitive(3));
assertEquals(new JsonPrimitive(2), old);
assertEquals(Collections.singleton(new SimpleEntry<>("b", new JsonPrimitive(3))), map.entrySet());
assertEquals(Collections.singleton(new SimpleEntry<>("b", new JsonPrimitive(3))), o.entrySet());
assertThat(old).isEqualTo(new JsonPrimitive(2));
assertThat(map.entrySet()).isEqualTo(Collections.singleton(new SimpleEntry<>("b", new JsonPrimitive(3))));
assertThat(o.entrySet()).isEqualTo(Collections.singleton(new SimpleEntry<>("b", new JsonPrimitive(3))));
try {
entry.setValue(null);
fail();
} catch (NullPointerException e) {
assertEquals("value == null", e.getMessage());
assertThat(e).hasMessageThat().isEqualTo("value == null");
}
}
@ -266,8 +262,8 @@ public class JsonObjectAsMapTest {
Map<String, JsonElement> map = o.asMap();
MoreAsserts.assertEqualsAndHashCode(map, Collections.singletonMap("a", new JsonPrimitive(1)));
assertFalse(map.equals(Collections.emptyMap()));
assertFalse(map.equals(Collections.singletonMap("a", new JsonPrimitive(2))));
assertThat(map.equals(Collections.emptyMap())).isFalse();
assertThat(map.equals(Collections.singletonMap("a", new JsonPrimitive(2)))).isFalse();
}
/** Verify that {@code JsonObject} updates are visible to view and vice versa */
@ -277,11 +273,11 @@ public class JsonObjectAsMapTest {
Map<String, JsonElement> map = o.asMap();
o.addProperty("a", 1);
assertEquals(1, map.size());
assertEquals(new JsonPrimitive(1), map.get("a"));
assertThat(map).hasSize(1);
assertThat(map.get("a")).isEqualTo(new JsonPrimitive(1));
map.put("b", new JsonPrimitive(2));
assertEquals(2, o.size());
assertEquals(new JsonPrimitive(2), o.get("b"));
assertThat(o.size()).isEqualTo(2);
assertThat(map.get("b")).isEqualTo(new JsonPrimitive(2));
}
}

View File

@ -16,11 +16,7 @@
package com.google.gson;
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.assertTrue;
import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.fail;
import com.google.gson.common.MoreAsserts;
@ -44,39 +40,39 @@ import org.junit.Test;
public class JsonObjectTest {
@Test
public void testAddingAndRemovingObjectProperties() throws Exception {
public void testAddingAndRemovingObjectProperties() {
JsonObject jsonObj = new JsonObject();
String propertyName = "property";
assertFalse(jsonObj.has(propertyName));
assertNull(jsonObj.get(propertyName));
assertThat(jsonObj.has(propertyName)).isFalse();
assertThat(jsonObj.get(propertyName)).isNull();
JsonPrimitive value = new JsonPrimitive("blah");
jsonObj.add(propertyName, value);
assertEquals(value, jsonObj.get(propertyName));
assertThat(jsonObj.get(propertyName)).isEqualTo(value);
JsonElement removedElement = jsonObj.remove(propertyName);
assertEquals(value, removedElement);
assertFalse(jsonObj.has(propertyName));
assertNull(jsonObj.get(propertyName));
assertThat(removedElement).isEqualTo(value);
assertThat(jsonObj.has(propertyName)).isFalse();
assertThat(jsonObj.get(propertyName)).isNull();
assertNull(jsonObj.remove(propertyName));
assertThat(jsonObj.remove(propertyName)).isNull();
}
@Test
public void testAddingNullPropertyValue() throws Exception {
public void testAddingNullPropertyValue() {
String propertyName = "property";
JsonObject jsonObj = new JsonObject();
jsonObj.add(propertyName, null);
assertTrue(jsonObj.has(propertyName));
assertThat(jsonObj.has(propertyName)).isTrue();
JsonElement jsonElement = jsonObj.get(propertyName);
assertNotNull(jsonElement);
assertTrue(jsonElement.isJsonNull());
assertThat(jsonElement).isNotNull();
assertThat(jsonElement.isJsonNull()).isTrue();
}
@Test
public void testAddingNullOrEmptyPropertyName() throws Exception {
public void testAddingNullOrEmptyPropertyName() {
JsonObject jsonObj = new JsonObject();
try {
jsonObj.add(null, JsonNull.INSTANCE);
@ -88,50 +84,50 @@ public class JsonObjectTest {
}
@Test
public void testAddingBooleanProperties() throws Exception {
public void testAddingBooleanProperties() {
String propertyName = "property";
JsonObject jsonObj = new JsonObject();
jsonObj.addProperty(propertyName, true);
assertTrue(jsonObj.has(propertyName));
assertThat(jsonObj.has(propertyName)).isTrue();
JsonElement jsonElement = jsonObj.get(propertyName);
assertNotNull(jsonElement);
assertTrue(jsonElement.getAsBoolean());
assertThat(jsonElement).isNotNull();
assertThat(jsonElement.getAsBoolean()).isTrue();
}
@Test
public void testAddingStringProperties() throws Exception {
public void testAddingStringProperties() {
String propertyName = "property";
String value = "blah";
JsonObject jsonObj = new JsonObject();
jsonObj.addProperty(propertyName, value);
assertTrue(jsonObj.has(propertyName));
assertThat(jsonObj.has(propertyName)).isTrue();
JsonElement jsonElement = jsonObj.get(propertyName);
assertNotNull(jsonElement);
assertEquals(value, jsonElement.getAsString());
assertThat(jsonElement).isNotNull();
assertThat(jsonElement.getAsString()).isEqualTo(value);
}
@Test
public void testAddingCharacterProperties() throws Exception {
public void testAddingCharacterProperties() {
String propertyName = "property";
char value = 'a';
JsonObject jsonObj = new JsonObject();
jsonObj.addProperty(propertyName, value);
assertTrue(jsonObj.has(propertyName));
assertThat(jsonObj.has(propertyName)).isTrue();
JsonElement jsonElement = jsonObj.get(propertyName);
assertNotNull(jsonElement);
assertEquals(String.valueOf(value), jsonElement.getAsString());
assertThat(jsonElement).isNotNull();
assertThat(jsonElement.getAsString()).isEqualTo(String.valueOf(value));
@SuppressWarnings("deprecation")
char character = jsonElement.getAsCharacter();
assertEquals(value, character);
assertThat(character).isEqualTo(value);
}
/**
@ -142,7 +138,7 @@ public class JsonObjectTest {
JsonObject jsonObj = new JsonObject();
jsonObj.add("a\"b", new JsonPrimitive("c\"d"));
String json = new Gson().toJson(jsonObj);
assertEquals("{\"a\\\"b\":\"c\\\"d\"}", json);
assertThat(json).isEqualTo("{\"a\\\"b\":\"c\\\"d\"}");
}
/**
@ -152,14 +148,13 @@ public class JsonObjectTest {
public void testWritePropertyWithEmptyStringName() {
JsonObject jsonObj = new JsonObject();
jsonObj.add("", new JsonPrimitive(true));
assertEquals("{\"\":true}", new Gson().toJson(jsonObj));
assertThat(new Gson().toJson(jsonObj)).isEqualTo("{\"\":true}");
}
@Test
public void testReadPropertyWithEmptyStringName() {
JsonObject jsonObj = JsonParser.parseString("{\"\":true}").getAsJsonObject();
assertEquals(true, jsonObj.get("").getAsBoolean());
assertThat(jsonObj.get("").getAsBoolean()).isTrue();
}
@Test
@ -172,22 +167,22 @@ public class JsonObjectTest {
JsonObject a = new JsonObject();
JsonObject b = new JsonObject();
assertEquals(a, a);
assertThat(a).isEqualTo(a);
a.add("foo", new JsonObject());
assertFalse(a.equals(b));
assertFalse(b.equals(a));
assertThat(a.equals(b)).isFalse();
assertThat(b.equals(a)).isFalse();
b.add("foo", new JsonObject());
MoreAsserts.assertEqualsAndHashCode(a, b);
a.add("bar", new JsonObject());
assertFalse(a.equals(b));
assertFalse(b.equals(a));
assertThat(a.equals(b)).isFalse();
assertThat(b.equals(a)).isFalse();
b.add("bar", JsonNull.INSTANCE);
assertFalse(a.equals(b));
assertFalse(b.equals(a));
assertThat(a.equals(b)).isFalse();
assertThat(b.equals(a)).isFalse();
}
@Test
@ -201,8 +196,8 @@ public class JsonObjectTest {
a.addProperty("2", false);
b.addProperty("1", true);
assertEquals(Arrays.asList("1", "2"), new ArrayList<>(a.keySet()));
assertEquals(Arrays.asList("2", "1"), new ArrayList<>(b.keySet()));
assertThat(new ArrayList<>(a.keySet())).containsExactly("1", "2").inOrder();
assertThat(new ArrayList<>(b.keySet())).containsExactly("2", "1").inOrder();
MoreAsserts.assertEqualsAndHashCode(a, b);
}
@ -210,28 +205,28 @@ public class JsonObjectTest {
@Test
public void testSize() {
JsonObject o = new JsonObject();
assertEquals(0, o.size());
assertThat(o.size()).isEqualTo(0);
o.add("Hello", new JsonPrimitive(1));
assertEquals(1, o.size());
assertThat(o.size()).isEqualTo(1);
o.add("Hi", new JsonPrimitive(1));
assertEquals(2, o.size());
assertThat(o.size()).isEqualTo(2);
o.remove("Hello");
assertEquals(1, o.size());
assertThat(o.size()).isEqualTo(1);
}
@Test
public void testIsEmpty() {
JsonObject o = new JsonObject();
assertTrue(o.isEmpty());
assertThat(o.isEmpty()).isTrue();
o.add("Hello", new JsonPrimitive(1));
assertFalse(o.isEmpty());
assertThat(o.isEmpty()).isFalse();
o.remove("Hello");
assertTrue(o.isEmpty());
assertThat(o.isEmpty()).isTrue();
}
@Test
@ -243,8 +238,8 @@ public class JsonObjectTest {
JsonObject copy = original.deepCopy();
firstEntry.add(new JsonPrimitive("z"));
assertEquals(1, original.get("key").getAsJsonArray().size());
assertEquals(0, copy.get("key").getAsJsonArray().size());
assertThat(original.get("key").getAsJsonArray()).hasSize(1);
assertThat(copy.get("key").getAsJsonArray()).hasSize(0);
}
/**
@ -253,15 +248,15 @@ public class JsonObjectTest {
@Test
public void testKeySet() {
JsonObject a = new JsonObject();
assertEquals(0, a.keySet().size());
assertThat(a.keySet()).hasSize(0);
a.add("foo", new JsonArray());
a.add("bar", new JsonObject());
assertEquals(2, a.size());
assertEquals(2, a.keySet().size());
assertTrue(a.keySet().contains("foo"));
assertTrue(a.keySet().contains("bar"));
assertThat(a.size()).isEqualTo(2);
assertThat(a.keySet()).hasSize(2);
assertThat(a.keySet().contains("foo")).isTrue();
assertThat(a.keySet().contains("bar")).isTrue();
a.addProperty("1", true);
a.addProperty("2", false);
@ -269,30 +264,30 @@ public class JsonObjectTest {
// Insertion order should be preserved by keySet()
Deque<String> expectedKeys = new ArrayDeque<>(Arrays.asList("foo", "bar", "1", "2"));
// Note: Must wrap in ArrayList because Deque implementations do not implement `equals`
assertEquals(new ArrayList<>(expectedKeys), new ArrayList<>(a.keySet()));
assertThat(new ArrayList<>(a.keySet())).isEqualTo(new ArrayList<>(expectedKeys));
Iterator<String> iterator = a.keySet().iterator();
// Remove keys one by one
for (int i = a.size(); i >= 1; i--) {
assertTrue(iterator.hasNext());
assertEquals(expectedKeys.getFirst(), iterator.next());
assertThat(iterator.hasNext()).isTrue();
assertThat(iterator.next()).isEqualTo(expectedKeys.getFirst());
iterator.remove();
expectedKeys.removeFirst();
assertEquals(i - 1, a.size());
assertEquals(new ArrayList<>(expectedKeys), new ArrayList<>(a.keySet()));
assertThat(a.size()).isEqualTo(i - 1);
assertThat(new ArrayList<>(a.keySet())).isEqualTo(new ArrayList<>(expectedKeys));
}
}
@Test
public void testEntrySet() {
JsonObject o = new JsonObject();
assertEquals(0, o.entrySet().size());
assertThat(o.entrySet()).hasSize(0);
o.addProperty("b", true);
Set<?> expectedEntries = Collections.singleton(new SimpleEntry<>("b", new JsonPrimitive(true)));
assertEquals(expectedEntries, o.entrySet());
assertEquals(1, o.entrySet().size());
assertThat(o.entrySet()).isEqualTo(expectedEntries);
assertThat(o.entrySet()).hasSize(1);
o.addProperty("a", false);
// Insertion order should be preserved by entrySet()
@ -300,7 +295,7 @@ public class JsonObjectTest {
new SimpleEntry<>("b", new JsonPrimitive(true)),
new SimpleEntry<>("a", new JsonPrimitive(false))
);
assertEquals(expectedEntriesList, new ArrayList<>(o.entrySet()));
assertThat(new ArrayList<>(o.entrySet())).isEqualTo(expectedEntriesList);
Iterator<Entry<String, JsonElement>> iterator = o.entrySet().iterator();
// Test behavior of Entry.setValue
@ -308,14 +303,14 @@ public class JsonObjectTest {
Entry<String, JsonElement> entry = iterator.next();
entry.setValue(new JsonPrimitive(i));
assertEquals(new JsonPrimitive(i), entry.getValue());
assertThat(entry.getValue()).isEqualTo(new JsonPrimitive(i));
}
expectedEntriesList = Arrays.asList(
new SimpleEntry<>("b", new JsonPrimitive(0)),
new SimpleEntry<>("a", new JsonPrimitive(1))
);
assertEquals(expectedEntriesList, new ArrayList<>(o.entrySet()));
assertThat(new ArrayList<>(o.entrySet())).isEqualTo(expectedEntriesList);
Entry<String, JsonElement> entry = o.entrySet().iterator().next();
try {
@ -325,9 +320,9 @@ public class JsonObjectTest {
entry.setValue(null);
fail();
} catch (NullPointerException e) {
assertEquals("value == null", e.getMessage());
assertThat(e).hasMessageThat().isEqualTo("value == null");
}
assertNotNull(entry.getValue());
assertThat(entry.getValue()).isNotNull();
o.addProperty("key1", 1);
o.addProperty("key2", 2);
@ -339,18 +334,18 @@ public class JsonObjectTest {
new SimpleEntry<>("key2", new JsonPrimitive(2))
));
// Note: Must wrap in ArrayList because Deque implementations do not implement `equals`
assertEquals(new ArrayList<>(expectedEntriesQueue), new ArrayList<>(o.entrySet()));
assertThat(new ArrayList<>(o.entrySet())).isEqualTo(new ArrayList<>(expectedEntriesQueue));
iterator = o.entrySet().iterator();
// Remove entries one by one
for (int i = o.size(); i >= 1; i--) {
assertTrue(iterator.hasNext());
assertEquals(expectedEntriesQueue.getFirst(), iterator.next());
assertThat(iterator.hasNext()).isTrue();
assertThat(iterator.next()).isEqualTo(expectedEntriesQueue.getFirst());
iterator.remove();
expectedEntriesQueue.removeFirst();
assertEquals(i - 1, o.size());
assertEquals(new ArrayList<>(expectedEntriesQueue), new ArrayList<>(o.entrySet()));
assertThat(o.size()).isEqualTo(i - 1);
assertThat(new ArrayList<>(o.entrySet())).isEqualTo(new ArrayList<>(expectedEntriesQueue));
}
}
}

View File

@ -1,8 +1,7 @@
package com.google.gson;
import static org.junit.Assert.assertEquals;
import static com.google.common.truth.Truth.assertThat;
import java.io.IOException;
import java.util.Arrays;
import org.junit.Test;
import org.junit.runner.RunWith;
@ -31,11 +30,11 @@ public class JsonParserParameterizedTest {
public String json;
@Test
public void testParse() throws IOException {
public void testParse() {
JsonElement deserialized = JsonParser.parseString(json);
String actualSerialized = adapter.toJson(deserialized);
// Serialized JsonElement should be the same as original JSON
assertEquals(json, actualSerialized);
assertThat(actualSerialized).isEqualTo(json);
}
}

View File

@ -16,8 +16,7 @@
package com.google.gson;
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.common.TestTypes.BagOfPrimitives;
@ -47,37 +46,37 @@ public class JsonParserTest {
@Test
public void testParseUnquotedStringArrayFails() {
JsonElement element = JsonParser.parseString("[a,b,c]");
assertEquals("a", element.getAsJsonArray().get(0).getAsString());
assertEquals("b", element.getAsJsonArray().get(1).getAsString());
assertEquals("c", element.getAsJsonArray().get(2).getAsString());
assertEquals(3, element.getAsJsonArray().size());
assertThat(element.getAsJsonArray().get(0).getAsString()).isEqualTo("a");
assertThat(element.getAsJsonArray().get(1).getAsString()).isEqualTo("b");
assertThat(element.getAsJsonArray().get(2).getAsString()).isEqualTo("c");
assertThat(element.getAsJsonArray()).hasSize(3);
}
@Test
public void testParseString() {
String json = "{a:10,b:'c'}";
JsonElement e = JsonParser.parseString(json);
assertTrue(e.isJsonObject());
assertEquals(10, e.getAsJsonObject().get("a").getAsInt());
assertEquals("c", e.getAsJsonObject().get("b").getAsString());
assertThat(e.isJsonObject()).isTrue();
assertThat(e.getAsJsonObject().get("a").getAsInt()).isEqualTo(10);
assertThat(e.getAsJsonObject().get("b").getAsString()).isEqualTo("c");
}
@Test
public void testParseEmptyString() {
JsonElement e = JsonParser.parseString("\" \"");
assertTrue(e.isJsonPrimitive());
assertEquals(" ", e.getAsString());
assertThat(e.isJsonPrimitive()).isTrue();
assertThat(e.getAsString()).isEqualTo(" ");
}
@Test
public void testParseEmptyWhitespaceInput() {
JsonElement e = JsonParser.parseString(" ");
assertTrue(e.isJsonNull());
assertThat(e.isJsonNull()).isTrue();
}
@Test
public void testParseUnquotedSingleWordStringFails() {
assertEquals("Test", JsonParser.parseString("Test").getAsString());
assertThat(JsonParser.parseString("Test").getAsString()).isEqualTo("Test");
}
@Test
@ -93,12 +92,12 @@ public class JsonParserTest {
public void testParseMixedArray() {
String json = "[{},13,\"stringValue\"]";
JsonElement e = JsonParser.parseString(json);
assertTrue(e.isJsonArray());
assertThat(e.isJsonArray()).isTrue();
JsonArray array = e.getAsJsonArray();
assertEquals("{}", array.get(0).toString());
assertEquals(13, array.get(1).getAsInt());
assertEquals("stringValue", array.get(2).getAsString());
assertThat(array.get(0).toString()).isEqualTo("{}");
assertThat(array.get(1).getAsInt()).isEqualTo(13);
assertThat(array.get(2).getAsString()).isEqualTo("stringValue");
}
private static String repeat(String s, int times) {
@ -123,10 +122,10 @@ public class JsonParserTest {
if (current.isEmpty()) {
break;
}
assertEquals(1, current.size());
assertThat(current.size()).isEqualTo(1);
current = current.get(0).getAsJsonArray();
}
assertEquals(times, actualTimes);
assertThat(actualTimes).isEqualTo(times);
}
/** Deeply nested JSON objects should not cause {@link StackOverflowError} */
@ -139,7 +138,7 @@ public class JsonParserTest {
int actualTimes = 0;
JsonObject current = JsonParser.parseString(json).getAsJsonObject();
while (true) {
assertEquals(1, current.size());
assertThat(current.size()).isEqualTo(1);
actualTimes++;
JsonElement next = current.get("a");
if (next.isJsonNull()) {
@ -148,16 +147,16 @@ public class JsonParserTest {
current = next.getAsJsonObject();
}
}
assertEquals(times, actualTimes);
assertThat(actualTimes).isEqualTo(times);
}
@Test
public void testParseReader() {
StringReader reader = new StringReader("{a:10,b:'c'}");
JsonElement e = JsonParser.parseReader(reader);
assertTrue(e.isJsonObject());
assertEquals(10, e.getAsJsonObject().get("a").getAsInt());
assertEquals("c", e.getAsJsonObject().get("b").getAsString());
assertThat(e.isJsonObject()).isTrue();
assertThat(e.getAsJsonObject().get("a").getAsInt()).isEqualTo(10);
assertThat(e.getAsJsonObject().get("b").getAsString()).isEqualTo("c");
}
@Test
@ -175,8 +174,8 @@ public class JsonParserTest {
JsonElement element1 = Streams.parse(parser);
JsonElement element2 = Streams.parse(parser);
BagOfPrimitives actualOne = gson.fromJson(element1, BagOfPrimitives.class);
assertEquals("one", actualOne.stringValue);
assertThat(actualOne.stringValue).isEqualTo("one");
BagOfPrimitives actualTwo = gson.fromJson(element2, BagOfPrimitives.class);
assertEquals("two", actualTwo.stringValue);
assertThat(actualTwo.stringValue).isEqualTo("two");
}
}

View File

@ -16,10 +16,8 @@
package com.google.gson;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertSame;
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.common.MoreAsserts;
@ -60,50 +58,50 @@ public class JsonPrimitiveTest {
}
@Test
public void testBoolean() throws Exception {
public void testBoolean() {
JsonPrimitive json = new JsonPrimitive(Boolean.TRUE);
assertTrue(json.isBoolean());
assertTrue(json.getAsBoolean());
assertThat(json.isBoolean()).isTrue();
assertThat(json.getAsBoolean()).isTrue();
// Extra support for booleans
json = new JsonPrimitive(1);
assertFalse(json.getAsBoolean());
assertThat(json.getAsBoolean()).isFalse();
json = new JsonPrimitive("1");
assertFalse(json.getAsBoolean());
assertThat(json.getAsBoolean()).isFalse();
json = new JsonPrimitive("true");
assertTrue(json.getAsBoolean());
assertThat(json.getAsBoolean()).isTrue();
json = new JsonPrimitive("TrUe");
assertTrue(json.getAsBoolean());
assertThat(json.getAsBoolean()).isTrue();
json = new JsonPrimitive("1.3");
assertFalse(json.getAsBoolean());
assertThat(json.getAsBoolean()).isFalse();
}
@Test
public void testParsingStringAsBoolean() throws Exception {
public void testParsingStringAsBoolean() {
JsonPrimitive json = new JsonPrimitive("true");
assertFalse(json.isBoolean());
assertTrue(json.getAsBoolean());
assertThat(json.isBoolean()).isFalse();
assertThat(json.getAsBoolean()).isTrue();
}
@Test
public void testParsingStringAsNumber() throws Exception {
public void testParsingStringAsNumber() {
JsonPrimitive json = new JsonPrimitive("1");
assertFalse(json.isNumber());
assertEquals(1D, json.getAsDouble(), 0.00001);
assertEquals(1F, json.getAsFloat(), 0.00001);
assertEquals(1, json.getAsInt());
assertEquals(1L, json.getAsLong());
assertEquals((short) 1, json.getAsShort());
assertEquals((byte) 1, json.getAsByte());
assertEquals(new BigInteger("1"), json.getAsBigInteger());
assertEquals(new BigDecimal("1"), json.getAsBigDecimal());
assertThat(json.isNumber()).isFalse();
assertThat(json.getAsDouble()).isEqualTo(1.0);
assertThat(json.getAsFloat()).isEqualTo(1F);
assertThat(json.getAsInt()).isEqualTo(1);
assertThat(json.getAsLong()).isEqualTo(1L);
assertThat(json.getAsShort()).isEqualTo((short) 1);
assertThat(json.getAsByte()).isEqualTo((byte) 1);
assertThat(json.getAsBigInteger()).isEqualTo(new BigInteger("1"));
assertThat(json.getAsBigDecimal()).isEqualTo(new BigDecimal("1"));
}
@Test
@ -113,43 +111,42 @@ public class JsonPrimitiveTest {
json.getAsNumber();
fail();
} catch (UnsupportedOperationException e) {
assertEquals("Primitive is neither a number nor a string", e.getMessage());
assertThat(e).hasMessageThat().isEqualTo("Primitive is neither a number nor a string");
}
}
@SuppressWarnings("deprecation")
@Test
public void testStringsAndChar() throws Exception {
public void testStringsAndChar() {
JsonPrimitive json = new JsonPrimitive("abc");
assertTrue(json.isString());
assertEquals('a', json.getAsCharacter());
assertEquals("abc", json.getAsString());
assertThat(json.isString()).isTrue();
assertThat(json.getAsCharacter()).isEqualTo('a');
assertThat(json.getAsString()).isEqualTo("abc");
json = new JsonPrimitive('z');
assertTrue(json.isString());
assertEquals('z', json.getAsCharacter());
assertEquals("z", json.getAsString());
assertThat(json.isString()).isTrue();
assertThat(json.getAsCharacter()).isEqualTo('z');
assertThat(json.getAsString()).isEqualTo("z");
json = new JsonPrimitive(true);
assertEquals("true", json.getAsString());
assertThat(json.getAsString()).isEqualTo("true");
json = new JsonPrimitive("");
assertEquals("", json.getAsString());
assertThat(json.getAsString()).isEqualTo("");
try {
json.getAsCharacter();
fail();
} catch (UnsupportedOperationException e) {
assertEquals("String value is empty", e.getMessage());
assertThat(e).hasMessageThat().isEqualTo("String value is empty");
}
}
@Test
public void testExponential() throws Exception {
public void testExponential() {
JsonPrimitive json = new JsonPrimitive("1E+7");
assertEquals(new BigDecimal("1E+7"), json.getAsBigDecimal());
assertEquals(1E+7, json.getAsDouble(), 0.00001);
assertEquals(1E+7, json.getAsDouble(), 0.00001);
assertThat(json.getAsBigDecimal()).isEqualTo(new BigDecimal("1E+7"));
assertThat(json.getAsDouble()).isEqualTo(1E+7);
try {
json.getAsInt();
@ -159,115 +156,115 @@ public class JsonPrimitiveTest {
@Test
public void testByteEqualsShort() {
JsonPrimitive p1 = new JsonPrimitive(Byte.valueOf((byte)10));
JsonPrimitive p2 = new JsonPrimitive(Short.valueOf((short)10));
assertEquals(p1, p2);
assertEquals(p1.hashCode(), p2.hashCode());
JsonPrimitive p1 = new JsonPrimitive((byte) 10);
JsonPrimitive p2 = new JsonPrimitive((short) 10);
assertThat(p1).isEqualTo(p2);
assertThat(p1.hashCode()).isEqualTo(p2.hashCode());
}
@Test
public void testByteEqualsInteger() {
JsonPrimitive p1 = new JsonPrimitive(Byte.valueOf((byte)10));
JsonPrimitive p2 = new JsonPrimitive(Integer.valueOf(10));
assertEquals(p1, p2);
assertEquals(p1.hashCode(), p2.hashCode());
JsonPrimitive p1 = new JsonPrimitive((byte) 10);
JsonPrimitive p2 = new JsonPrimitive(10);
assertThat(p1).isEqualTo(p2);
assertThat(p1.hashCode()).isEqualTo(p2.hashCode());
}
@Test
public void testByteEqualsLong() {
JsonPrimitive p1 = new JsonPrimitive(Byte.valueOf((byte)10));
JsonPrimitive p2 = new JsonPrimitive(Long.valueOf(10L));
assertEquals(p1, p2);
assertEquals(p1.hashCode(), p2.hashCode());
JsonPrimitive p1 = new JsonPrimitive((byte) 10);
JsonPrimitive p2 = new JsonPrimitive(10L);
assertThat(p1).isEqualTo(p2);
assertThat(p1.hashCode()).isEqualTo(p2.hashCode());
}
@Test
public void testByteEqualsBigInteger() {
JsonPrimitive p1 = new JsonPrimitive(Byte.valueOf((byte)10));
JsonPrimitive p1 = new JsonPrimitive((byte) 10);
JsonPrimitive p2 = new JsonPrimitive(new BigInteger("10"));
assertEquals(p1, p2);
assertEquals(p1.hashCode(), p2.hashCode());
assertThat(p1).isEqualTo(p2);
assertThat(p1.hashCode()).isEqualTo(p2.hashCode());
}
@Test
public void testShortEqualsInteger() {
JsonPrimitive p1 = new JsonPrimitive(Short.valueOf((short)10));
JsonPrimitive p2 = new JsonPrimitive(Integer.valueOf(10));
assertEquals(p1, p2);
assertEquals(p1.hashCode(), p2.hashCode());
JsonPrimitive p1 = new JsonPrimitive((short) 10);
JsonPrimitive p2 = new JsonPrimitive(10);
assertThat(p1).isEqualTo(p2);
assertThat(p1.hashCode()).isEqualTo(p2.hashCode());
}
@Test
public void testShortEqualsLong() {
JsonPrimitive p1 = new JsonPrimitive(Short.valueOf((short)10));
JsonPrimitive p2 = new JsonPrimitive(Long.valueOf(10));
assertEquals(p1, p2);
assertEquals(p1.hashCode(), p2.hashCode());
JsonPrimitive p1 = new JsonPrimitive((short) 10);
JsonPrimitive p2 = new JsonPrimitive(10L);
assertThat(p1).isEqualTo(p2);
assertThat(p1.hashCode()).isEqualTo(p2.hashCode());
}
@Test
public void testShortEqualsBigInteger() {
JsonPrimitive p1 = new JsonPrimitive(Short.valueOf((short)10));
JsonPrimitive p1 = new JsonPrimitive((short) 10);
JsonPrimitive p2 = new JsonPrimitive(new BigInteger("10"));
assertEquals(p1, p2);
assertEquals(p1.hashCode(), p2.hashCode());
assertThat(p1).isEqualTo(p2);
assertThat(p1.hashCode()).isEqualTo(p2.hashCode());
}
@Test
public void testIntegerEqualsLong() {
JsonPrimitive p1 = new JsonPrimitive(Integer.valueOf(10));
JsonPrimitive p2 = new JsonPrimitive(Long.valueOf(10L));
assertEquals(p1, p2);
assertEquals(p1.hashCode(), p2.hashCode());
JsonPrimitive p1 = new JsonPrimitive(10);
JsonPrimitive p2 = new JsonPrimitive(10L);
assertThat(p1).isEqualTo(p2);
assertThat(p1.hashCode()).isEqualTo(p2.hashCode());
}
@Test
public void testIntegerEqualsBigInteger() {
JsonPrimitive p1 = new JsonPrimitive(Integer.valueOf(10));
JsonPrimitive p1 = new JsonPrimitive(10);
JsonPrimitive p2 = new JsonPrimitive(new BigInteger("10"));
assertEquals(p1, p2);
assertEquals(p1.hashCode(), p2.hashCode());
assertThat(p1).isEqualTo(p2);
assertThat(p1.hashCode()).isEqualTo(p2.hashCode());
}
@Test
public void testLongEqualsBigInteger() {
JsonPrimitive p1 = new JsonPrimitive(Long.valueOf(10L));
JsonPrimitive p1 = new JsonPrimitive(10L);
JsonPrimitive p2 = new JsonPrimitive(new BigInteger("10"));
assertEquals(p1, p2);
assertEquals(p1.hashCode(), p2.hashCode());
assertThat(p1).isEqualTo(p2);
assertThat(p1.hashCode()).isEqualTo(p2.hashCode());
}
@Test
public void testFloatEqualsDouble() {
JsonPrimitive p1 = new JsonPrimitive(Float.valueOf(10.25F));
JsonPrimitive p2 = new JsonPrimitive(Double.valueOf(10.25D));
assertEquals(p1, p2);
assertEquals(p1.hashCode(), p2.hashCode());
JsonPrimitive p1 = new JsonPrimitive(10.25F);
JsonPrimitive p2 = new JsonPrimitive(10.25D);
assertThat(p1).isEqualTo(p2);
assertThat(p1.hashCode()).isEqualTo(p2.hashCode());
}
@Test
public void testFloatEqualsBigDecimal() {
JsonPrimitive p1 = new JsonPrimitive(Float.valueOf(10.25F));
JsonPrimitive p1 = new JsonPrimitive(10.25F);
JsonPrimitive p2 = new JsonPrimitive(new BigDecimal("10.25"));
assertEquals(p1, p2);
assertEquals(p1.hashCode(), p2.hashCode());
assertThat(p1).isEqualTo(p2);
assertThat(p1.hashCode()).isEqualTo(p2.hashCode());
}
@Test
public void testDoubleEqualsBigDecimal() {
JsonPrimitive p1 = new JsonPrimitive(Double.valueOf(10.25D));
JsonPrimitive p1 = new JsonPrimitive(10.25D);
JsonPrimitive p2 = new JsonPrimitive(new BigDecimal("10.25"));
assertEquals(p1, p2);
assertEquals(p1.hashCode(), p2.hashCode());
assertThat(p1).isEqualTo(p2);
assertThat(p1.hashCode()).isEqualTo(p2.hashCode());
}
@Test
public void testValidJsonOnToString() throws Exception {
public void testValidJsonOnToString() {
JsonPrimitive json = new JsonPrimitive("Some\nEscaped\nValue");
assertEquals("\"Some\\nEscaped\\nValue\"", json.toString());
assertThat(json.toString()).isEqualTo("\"Some\\nEscaped\\nValue\"");
json = new JsonPrimitive(new BigDecimal("1.333"));
assertEquals("1.333", json.toString());
assertThat(json.toString()).isEqualTo("1.333");
}
@Test
@ -286,9 +283,9 @@ public class JsonPrimitiveTest {
new JsonPrimitive(Double.NEGATIVE_INFINITY));
MoreAsserts.assertEqualsAndHashCode(new JsonPrimitive(Double.POSITIVE_INFINITY),
new JsonPrimitive(Double.POSITIVE_INFINITY));
assertFalse(new JsonPrimitive("a").equals(new JsonPrimitive("b")));
assertFalse(new JsonPrimitive(true).equals(new JsonPrimitive(false)));
assertFalse(new JsonPrimitive(0).equals(new JsonPrimitive(1)));
assertThat(new JsonPrimitive("a").equals(new JsonPrimitive("b"))).isFalse();
assertThat(new JsonPrimitive(true).equals(new JsonPrimitive(false))).isFalse();
assertThat(new JsonPrimitive(0).equals(new JsonPrimitive(1))).isFalse();
}
@Test
@ -306,19 +303,19 @@ public class JsonPrimitiveTest {
JsonPrimitive b = new JsonPrimitive(new BigInteger("18446744073709551621")); // 2^64 + 5
// Ideally, the following assertion should have failed but the price is too much to pay
// assertFalse(a + " equals " + b, a.equals(b));
assertTrue(a + " equals " + b, a.equals(b));
assertWithMessage("%s equals %s", a, b).that(a.equals(b)).isTrue();
}
@Test
public void testEqualsDoesNotEquateStringAndNonStringTypes() {
assertFalse(new JsonPrimitive("true").equals(new JsonPrimitive(true)));
assertFalse(new JsonPrimitive("0").equals(new JsonPrimitive(0)));
assertFalse(new JsonPrimitive("NaN").equals(new JsonPrimitive(Float.NaN)));
assertThat(new JsonPrimitive("true").equals(new JsonPrimitive(true))).isFalse();
assertThat(new JsonPrimitive("0").equals(new JsonPrimitive(0))).isFalse();
assertThat(new JsonPrimitive("NaN").equals(new JsonPrimitive(Float.NaN))).isFalse();
}
@Test
public void testDeepCopy() {
JsonPrimitive a = new JsonPrimitive("a");
assertSame(a, a.deepCopy()); // Primitives are immutable!
assertThat(a).isSameInstanceAs(a.deepCopy()); // Primitives are immutable!
}
}

View File

@ -15,9 +15,7 @@
*/
package com.google.gson;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.fail;
import java.io.EOFException;
@ -41,33 +39,33 @@ public class JsonStreamParserTest {
@Test
public void testParseTwoStrings() {
String actualOne = parser.next().getAsString();
assertEquals("one", actualOne);
assertThat(actualOne).isEqualTo("one");
String actualTwo = parser.next().getAsString();
assertEquals("two", actualTwo);
assertThat(actualTwo).isEqualTo("two");
}
@Test
public void testIterator() {
assertTrue(parser.hasNext());
assertEquals("one", parser.next().getAsString());
assertTrue(parser.hasNext());
assertEquals("two", parser.next().getAsString());
assertFalse(parser.hasNext());
assertThat(parser.hasNext()).isTrue();
assertThat(parser.next().getAsString()).isEqualTo("one");
assertThat(parser.hasNext()).isTrue();
assertThat(parser.next().getAsString()).isEqualTo("two");
assertThat(parser.hasNext()).isFalse();
}
@Test
public void testNoSideEffectForHasNext() throws Exception {
assertTrue(parser.hasNext());
assertTrue(parser.hasNext());
assertTrue(parser.hasNext());
assertEquals("one", parser.next().getAsString());
public void testNoSideEffectForHasNext() {
assertThat(parser.hasNext()).isTrue();
assertThat(parser.hasNext()).isTrue();
assertThat(parser.hasNext()).isTrue();
assertThat(parser.next().getAsString()).isEqualTo("one");
assertTrue(parser.hasNext());
assertTrue(parser.hasNext());
assertEquals("two", parser.next().getAsString());
assertThat(parser.hasNext()).isTrue();
assertThat(parser.hasNext()).isTrue();
assertThat(parser.next().getAsString()).isEqualTo("two");
assertFalse(parser.hasNext());
assertFalse(parser.hasNext());
assertThat(parser.hasNext()).isFalse();
assertThat(parser.hasNext()).isFalse();
}
@Test
@ -88,7 +86,7 @@ public class JsonStreamParserTest {
parser.next();
fail();
} catch (JsonIOException e) {
assertTrue(e.getCause() instanceof EOFException);
assertThat(e.getCause()).isInstanceOf(EOFException.class);
}
parser = new JsonStreamParser("");
@ -96,14 +94,14 @@ public class JsonStreamParserTest {
parser.hasNext();
fail();
} catch (JsonIOException e) {
assertTrue(e.getCause() instanceof EOFException);
assertThat(e.getCause()).isInstanceOf(EOFException.class);
}
}
@Test
public void testIncompleteInput() {
JsonStreamParser parser = new JsonStreamParser("[");
assertTrue(parser.hasNext());
assertThat(parser.hasNext()).isTrue();
try {
parser.next();
fail();

View File

@ -16,9 +16,7 @@
package com.google.gson;
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 org.junit.Test;
@ -33,12 +31,12 @@ public class LongSerializationPolicyTest {
@Test
public void testDefaultLongSerialization() throws Exception {
JsonElement element = LongSerializationPolicy.DEFAULT.serialize(1556L);
assertTrue(element.isJsonPrimitive());
assertThat(element.isJsonPrimitive()).isTrue();
JsonPrimitive jsonPrimitive = element.getAsJsonPrimitive();
assertFalse(jsonPrimitive.isString());
assertTrue(jsonPrimitive.isNumber());
assertEquals(1556L, element.getAsLong());
assertThat(jsonPrimitive.isString()).isFalse();
assertThat(jsonPrimitive.isNumber()).isTrue();
assertThat(element.getAsLong()).isEqualTo(1556L);
}
@Test
@ -46,30 +44,30 @@ public class LongSerializationPolicyTest {
Gson gson = new GsonBuilder()
.setLongSerializationPolicy(LongSerializationPolicy.DEFAULT)
.create();
assertEquals("[1]", gson.toJson(new long[] { 1L }, long[].class));
assertEquals("[1]", gson.toJson(new Long[] { 1L }, Long[].class));
assertThat(gson.toJson(new long[] { 1L }, long[].class)).isEqualTo("[1]");
assertThat(gson.toJson(new Long[] { 1L }, Long[].class)).isEqualTo("[1]");
}
@Test
public void testDefaultLongSerializationNull() {
LongSerializationPolicy policy = LongSerializationPolicy.DEFAULT;
assertTrue(policy.serialize(null).isJsonNull());
assertThat(policy.serialize(null).isJsonNull()).isTrue();
Gson gson = new GsonBuilder()
.setLongSerializationPolicy(policy)
.create();
assertEquals("null", gson.toJson(null, Long.class));
assertThat(gson.toJson(null, Long.class)).isEqualTo("null");
}
@Test
public void testStringLongSerialization() throws Exception {
JsonElement element = LongSerializationPolicy.STRING.serialize(1556L);
assertTrue(element.isJsonPrimitive());
assertThat(element.isJsonPrimitive()).isTrue();
JsonPrimitive jsonPrimitive = element.getAsJsonPrimitive();
assertFalse(jsonPrimitive.isNumber());
assertTrue(jsonPrimitive.isString());
assertEquals("1556", element.getAsString());
assertThat(jsonPrimitive.isNumber()).isFalse();
assertThat(jsonPrimitive.isString()).isTrue();
assertThat(element.getAsString()).isEqualTo("1556");
}
@Test
@ -77,18 +75,18 @@ public class LongSerializationPolicyTest {
Gson gson = new GsonBuilder()
.setLongSerializationPolicy(LongSerializationPolicy.STRING)
.create();
assertEquals("[\"1\"]", gson.toJson(new long[] { 1L }, long[].class));
assertEquals("[\"1\"]", gson.toJson(new Long[] { 1L }, Long[].class));
assertThat(gson.toJson(new long[] { 1L }, long[].class)).isEqualTo("[\"1\"]");
assertThat(gson.toJson(new Long[] { 1L }, long[].class)).isEqualTo("[\"1\"]");
}
@Test
public void testStringLongSerializationNull() {
LongSerializationPolicy policy = LongSerializationPolicy.STRING;
assertTrue(policy.serialize(null).isJsonNull());
assertThat(policy.serialize(null).isJsonNull()).isTrue();
Gson gson = new GsonBuilder()
.setLongSerializationPolicy(policy)
.create();
assertEquals("null", gson.toJson(null, Long.class));
assertThat(gson.toJson(null, Long.class)).isEqualTo("null");
}
}

View File

@ -16,9 +16,7 @@
package com.google.gson;
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.reflect.TypeToken;
@ -65,7 +63,7 @@ public final class MixedStreamTest {
gson.toJson(RED_MIATA, Car.class, jsonWriter);
jsonWriter.endArray();
assertEquals(CARS_JSON, stringWriter.toString());
assertThat(stringWriter.toString()).isEqualTo(CARS_JSON);
}
@Test
@ -75,9 +73,11 @@ public final class MixedStreamTest {
JsonReader jsonReader = new JsonReader(stringReader);
jsonReader.beginArray();
assertEquals(BLUE_MUSTANG, gson.fromJson(jsonReader, Car.class));
assertEquals(BLACK_BMW, gson.fromJson(jsonReader, Car.class));
assertEquals(RED_MIATA, gson.fromJson(jsonReader, Car.class));
// actual and expected object are inverted in the test.
// gson.fromJson(jsonReader, Car.class) as arg of assertThat() cause an ambiguous method call
assertThat(BLUE_MUSTANG).isEqualTo(gson.fromJson(jsonReader, Car.class));
assertThat(BLACK_BMW).isEqualTo(gson.fromJson(jsonReader, Car.class));
assertThat(RED_MIATA).isEqualTo(gson.fromJson(jsonReader, Car.class));
jsonReader.endArray();
}
@ -89,11 +89,11 @@ public final class MixedStreamTest {
jsonReader.setLenient(false);
gson.fromJson(jsonReader, Car.class);
assertFalse(jsonReader.isLenient());
assertThat(jsonReader.isLenient()).isFalse();
jsonReader.setLenient(true);
gson.fromJson(jsonReader, Car.class);
assertTrue(jsonReader.isLenient());
assertThat(jsonReader.isLenient()).isTrue();
}
@Test
@ -105,14 +105,14 @@ public final class MixedStreamTest {
jsonWriter.setHtmlSafe(true);
jsonWriter.setLenient(true);
gson.toJson(BLUE_MUSTANG, Car.class, jsonWriter);
assertTrue(jsonWriter.isHtmlSafe());
assertTrue(jsonWriter.isLenient());
assertThat(jsonWriter.isHtmlSafe()).isTrue();
assertThat(jsonWriter.isLenient()).isTrue();
jsonWriter.setHtmlSafe(false);
jsonWriter.setLenient(false);
gson.toJson(BLUE_MUSTANG, Car.class, jsonWriter);
assertFalse(jsonWriter.isHtmlSafe());
assertFalse(jsonWriter.isLenient());
assertThat(jsonWriter.isHtmlSafe()).isFalse();
assertThat(jsonWriter.isLenient()).isFalse();
}
@Test
@ -177,7 +177,7 @@ public final class MixedStreamTest {
StringWriter stringWriter = new StringWriter();
gson.toJson(null, new JsonWriter(stringWriter));
assertEquals("null", stringWriter.toString());
assertThat(stringWriter.toString()).isEqualTo("null");
}
@Test
@ -202,14 +202,14 @@ public final class MixedStreamTest {
StringWriter writer = new StringWriter();
new Gson().toJson(contents, type, new JsonWriter(writer));
assertEquals("[\"\\u003c\",\"\\u003e\",\"\\u0026\",\"\\u003d\",\"\\u0027\"]",
writer.toString());
assertThat(writer.toString())
.isEqualTo("[\"\\u003c\",\"\\u003e\",\"\\u0026\",\"\\u003d\",\"\\u0027\"]");
writer = new StringWriter();
new GsonBuilder().disableHtmlEscaping().create()
.toJson(contents, type, new JsonWriter(writer));
assertEquals("[\"<\",\">\",\"&\",\"=\",\"'\"]",
writer.toString());
assertThat(writer.toString())
.isEqualTo("[\"<\",\">\",\"&\",\"=\",\"'\"]");
}
@Test
@ -222,7 +222,7 @@ public final class MixedStreamTest {
JsonWriter jsonWriter = new JsonWriter(writer);
new GsonBuilder().serializeSpecialFloatingPointValues().create()
.toJson(doubles, type, jsonWriter);
assertEquals("[NaN,-Infinity,Infinity,-0.0,0.5,0.0]", writer.toString());
assertThat(writer.toString()).isEqualTo("[NaN,-Infinity,Infinity,-0.0,0.5,0.0]");
try {
new Gson().toJson(doubles, type, new JsonWriter(new StringWriter()));

View File

@ -1,6 +1,6 @@
package com.google.gson;
import static org.junit.Assert.assertEquals;
import static com.google.common.truth.Truth.assertThat;
import java.io.IOException;
import java.util.Arrays;
@ -36,6 +36,6 @@ public class ObjectTypeAdapterParameterizedTest {
String actualSerialized = adapter.toJson(deserialized);
// Serialized Object should be the same as original JSON
assertEquals(json, actualSerialized);
assertThat(actualSerialized).isEqualTo(json);
}
}

View File

@ -16,7 +16,7 @@
package com.google.gson;
import static org.junit.Assert.assertEquals;
import static com.google.common.truth.Truth.assertThat;
import java.io.IOException;
import java.util.Arrays;
@ -33,35 +33,35 @@ public final class ObjectTypeAdapterTest {
@Test
public void testDeserialize() throws Exception {
Map<?, ?> map = (Map<?, ?>) adapter.fromJson("{\"a\":5,\"b\":[1,2,null],\"c\":{\"x\":\"y\"}}");
assertEquals(5.0, map.get("a"));
assertEquals(Arrays.asList(1.0, 2.0, null), map.get("b"));
assertEquals(Collections.singletonMap("x", "y"), map.get("c"));
assertEquals(3, map.size());
assertThat(map.get("a")).isEqualTo(5.0);
assertThat(map.get("b")).isEqualTo(Arrays.asList(1.0, 2.0, null));
assertThat(map.get("c")).isEqualTo(Collections.singletonMap("x", "y"));
assertThat(map).hasSize(3);
}
@Test
public void testSerialize() throws Exception {
public void testSerialize() {
Object object = new RuntimeType();
assertEquals("{'a':5,'b':[1,2,null]}", adapter.toJson(object).replace("\"", "'"));
assertThat(adapter.toJson(object).replace("\"", "'")).isEqualTo("{'a':5,'b':[1,2,null]}");
}
@Test
public void testSerializeNullValue() throws Exception {
public void testSerializeNullValue() {
Map<String, Object> map = new LinkedHashMap<>();
map.put("a", null);
assertEquals("{'a':null}", adapter.toJson(map).replace('"', '\''));
assertThat(adapter.toJson(map).replace('"', '\'')).isEqualTo("{'a':null}");
}
@Test
public void testDeserializeNullValue() throws Exception {
Map<String, Object> map = new LinkedHashMap<>();
map.put("a", null);
assertEquals(map, adapter.fromJson("{\"a\":null}"));
assertThat(adapter.fromJson("{\"a\":null}")).isEqualTo(map);
}
@Test
public void testSerializeObject() throws Exception {
assertEquals("{}", adapter.toJson(new Object()));
public void testSerializeObject() {
assertThat(adapter.toJson(new Object())).isEqualTo("{}");
}
private static String repeat(String s, int times) {
@ -87,10 +87,10 @@ public final class ObjectTypeAdapterTest {
if (current.isEmpty()) {
break;
}
assertEquals(1, current.size());
assertThat(current).hasSize(1);
current = (List<List<?>>) current.get(0);
}
assertEquals(times, actualTimes);
assertThat(actualTimes).isEqualTo(times);
}
/** Deeply nested JSON objects should not cause {@link StackOverflowError} */
@ -104,11 +104,11 @@ public final class ObjectTypeAdapterTest {
int actualTimes = 0;
Map<String, Map<?, ?>> current = (Map<String, Map<?, ?>>) adapter.fromJson(json);
while (current != null) {
assertEquals(1, current.size());
assertThat(current).hasSize(1);
actualTimes++;
current = (Map<String, Map<?, ?>>) current.get("a");
}
assertEquals(times, actualTimes);
assertThat(actualTimes).isEqualTo(times);
}
@SuppressWarnings("unused")

View File

@ -16,7 +16,7 @@
package com.google.gson;
import static org.junit.Assert.assertEquals;
import static com.google.common.truth.Truth.assertThat;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
@ -52,11 +52,11 @@ public class OverrideCoreTypeAdaptersTest {
Gson gson = new GsonBuilder()
.registerTypeAdapter(Boolean.class, booleanAsIntAdapter)
.create();
assertEquals("true", gson.toJson(true, boolean.class));
assertEquals("1", gson.toJson(true, Boolean.class));
assertEquals(Boolean.TRUE, gson.fromJson("true", boolean.class));
assertEquals(Boolean.TRUE, gson.fromJson("1", Boolean.class));
assertEquals(Boolean.FALSE, gson.fromJson("0", Boolean.class));
assertThat(gson.toJson(true, boolean.class)).isEqualTo("true");
assertThat(gson.toJson(true, Boolean.class)).isEqualTo("1");
assertThat(gson.fromJson("true", boolean.class)).isEqualTo(Boolean.TRUE);
assertThat(gson.fromJson("1", Boolean.class)).isEqualTo(Boolean.TRUE);
assertThat(gson.fromJson("0", Boolean.class)).isEqualTo(Boolean.FALSE);
}
@Test
@ -64,11 +64,11 @@ public class OverrideCoreTypeAdaptersTest {
Gson gson = new GsonBuilder()
.registerTypeAdapter(boolean.class, booleanAsIntAdapter)
.create();
assertEquals("1", gson.toJson(true, boolean.class));
assertEquals("true", gson.toJson(true, Boolean.class));
assertEquals(Boolean.TRUE, gson.fromJson("1", boolean.class));
assertEquals(Boolean.TRUE, gson.fromJson("true", Boolean.class));
assertEquals("0", gson.toJson(false, boolean.class));
assertThat(gson.toJson(true, boolean.class)).isEqualTo("1");
assertThat(gson.toJson(true, Boolean.class)).isEqualTo("true");
assertThat(gson.fromJson("1", boolean.class)).isEqualTo(Boolean.TRUE);
assertThat(gson.fromJson("true", Boolean.class)).isEqualTo(Boolean.TRUE);
assertThat(gson.toJson(false, boolean.class)).isEqualTo("0");
}
@Test
@ -76,7 +76,7 @@ public class OverrideCoreTypeAdaptersTest {
Gson gson = new GsonBuilder()
.registerTypeAdapter(String.class, swapCaseStringAdapter)
.create();
assertEquals("\"HELLO\"", gson.toJson("Hello", String.class));
assertEquals("hello", gson.fromJson("\"Hello\"", String.class));
assertThat(gson.toJson("Hello", String.class)).isEqualTo("\"HELLO\"");
assertThat(gson.fromJson("\"Hello\"", String.class)).isEqualTo("hello");
}
}

View File

@ -16,9 +16,7 @@
package com.google.gson;
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.internal.$Gson$Types;
import com.google.gson.reflect.TypeToken;
@ -43,19 +41,19 @@ public class ParameterizedTypeTest {
}
@Test
public void testOurTypeFunctionality() throws Exception {
public void testOurTypeFunctionality() {
Type parameterizedType = new TypeToken<List<String>>() {}.getType();
assertNull(ourType.getOwnerType());
assertEquals(String.class, ourType.getActualTypeArguments()[0]);
assertEquals(List.class, ourType.getRawType());
assertEquals(parameterizedType, ourType);
assertEquals(parameterizedType.hashCode(), ourType.hashCode());
assertThat(ourType.getOwnerType()).isNull();
assertThat(ourType.getActualTypeArguments()[0]).isSameInstanceAs(String.class);
assertThat(ourType.getRawType()).isSameInstanceAs(List.class);
assertThat(ourType).isEqualTo(parameterizedType);
assertThat(ourType.hashCode()).isEqualTo(parameterizedType.hashCode());
}
@Test
public void testNotEquals() throws Exception {
public void testNotEquals() {
Type differentParameterizedType = new TypeToken<List<Integer>>() {}.getType();
assertFalse(differentParameterizedType.equals(ourType));
assertFalse(ourType.equals(differentParameterizedType));
assertThat(differentParameterizedType.equals(ourType)).isFalse();
assertThat(ourType.equals(differentParameterizedType)).isFalse();
}
}

View File

@ -16,7 +16,7 @@
package com.google.gson;
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;
@ -31,13 +31,13 @@ public class ToNumberPolicyTest {
@Test
public void testDouble() throws IOException {
ToNumberStrategy strategy = ToNumberPolicy.DOUBLE;
assertEquals(10.1, strategy.readNumber(fromString("10.1")));
assertEquals(3.141592653589793D, strategy.readNumber(fromString("3.141592653589793238462643383279")));
assertThat(strategy.readNumber(fromString("10.1"))).isEqualTo(10.1);
assertThat(strategy.readNumber(fromString("3.141592653589793238462643383279"))).isEqualTo(3.141592653589793D);
try {
strategy.readNumber(fromString("1e400"));
fail();
} catch (MalformedJsonException expected) {
assertEquals("JSON forbids NaN and infinities: Infinity at line 1 column 6 path $", expected.getMessage());
assertThat(expected).hasMessageThat().isEqualTo("JSON forbids NaN and infinities: Infinity at line 1 column 6 path $");
}
try {
strategy.readNumber(fromString("\"not-a-number\""));
@ -49,65 +49,65 @@ public class ToNumberPolicyTest {
@Test
public void testLazilyParsedNumber() throws IOException {
ToNumberStrategy strategy = ToNumberPolicy.LAZILY_PARSED_NUMBER;
assertEquals(new LazilyParsedNumber("10.1"), strategy.readNumber(fromString("10.1")));
assertEquals(new LazilyParsedNumber("3.141592653589793238462643383279"), strategy.readNumber(fromString("3.141592653589793238462643383279")));
assertEquals(new LazilyParsedNumber("1e400"), strategy.readNumber(fromString("1e400")));
assertThat(strategy.readNumber(fromString("10.1"))).isEqualTo(new LazilyParsedNumber("10.1"));
assertThat(strategy.readNumber(fromString("3.141592653589793238462643383279"))).isEqualTo(new LazilyParsedNumber("3.141592653589793238462643383279"));
assertThat(strategy.readNumber(fromString("1e400"))).isEqualTo(new LazilyParsedNumber("1e400"));
}
@Test
public void testLongOrDouble() throws IOException {
ToNumberStrategy strategy = ToNumberPolicy.LONG_OR_DOUBLE;
assertEquals(10L, strategy.readNumber(fromString("10")));
assertEquals(10.1, strategy.readNumber(fromString("10.1")));
assertEquals(3.141592653589793D, strategy.readNumber(fromString("3.141592653589793238462643383279")));
assertThat(strategy.readNumber(fromString("10"))).isEqualTo(10L);
assertThat(strategy.readNumber(fromString("10.1"))).isEqualTo(10.1);
assertThat(strategy.readNumber(fromString("3.141592653589793238462643383279"))).isEqualTo(3.141592653589793D);
try {
strategy.readNumber(fromString("1e400"));
fail();
} catch (MalformedJsonException expected) {
assertEquals("JSON forbids NaN and infinities: Infinity; at path $", expected.getMessage());
assertThat(expected).hasMessageThat().isEqualTo("JSON forbids NaN and infinities: Infinity; at path $");
}
try {
strategy.readNumber(fromString("\"not-a-number\""));
fail();
} catch (JsonParseException expected) {
assertEquals("Cannot parse not-a-number; at path $", expected.getMessage());
assertThat(expected).hasMessageThat().isEqualTo("Cannot parse not-a-number; at path $");
}
assertEquals(Double.NaN, strategy.readNumber(fromStringLenient("NaN")));
assertEquals(Double.POSITIVE_INFINITY, strategy.readNumber(fromStringLenient("Infinity")));
assertEquals(Double.NEGATIVE_INFINITY, strategy.readNumber(fromStringLenient("-Infinity")));
assertThat(strategy.readNumber(fromStringLenient("NaN"))).isEqualTo(Double.NaN);
assertThat(strategy.readNumber(fromStringLenient("Infinity"))).isEqualTo(Double.POSITIVE_INFINITY);
assertThat(strategy.readNumber(fromStringLenient("-Infinity"))).isEqualTo(Double.NEGATIVE_INFINITY);
try {
strategy.readNumber(fromString("NaN"));
fail();
} catch (MalformedJsonException expected) {
assertEquals("Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path $", expected.getMessage());
assertThat(expected).hasMessageThat().isEqualTo("Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path $");
}
try {
strategy.readNumber(fromString("Infinity"));
fail();
} catch (MalformedJsonException expected) {
assertEquals("Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path $", expected.getMessage());
assertThat(expected).hasMessageThat().isEqualTo("Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path $");
}
try {
strategy.readNumber(fromString("-Infinity"));
fail();
} catch (MalformedJsonException expected) {
assertEquals("Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path $", expected.getMessage());
assertThat(expected).hasMessageThat().isEqualTo("Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path $");
}
}
@Test
public void testBigDecimal() throws IOException {
ToNumberStrategy strategy = ToNumberPolicy.BIG_DECIMAL;
assertEquals(new BigDecimal("10.1"), strategy.readNumber(fromString("10.1")));
assertEquals(new BigDecimal("3.141592653589793238462643383279"), strategy.readNumber(fromString("3.141592653589793238462643383279")));
assertEquals(new BigDecimal("1e400"), strategy.readNumber(fromString("1e400")));
assertThat(strategy.readNumber(fromString("10.1"))).isEqualTo(new BigDecimal("10.1"));
assertThat(strategy.readNumber(fromString("3.141592653589793238462643383279"))).isEqualTo(new BigDecimal("3.141592653589793238462643383279"));
assertThat(strategy.readNumber(fromString("1e400"))).isEqualTo(new BigDecimal("1e400"));
try {
strategy.readNumber(fromString("\"not-a-number\""));
fail();
} catch (JsonParseException expected) {
assertEquals("Cannot parse not-a-number; at path $", expected.getMessage());
assertThat(expected).hasMessageThat().isEqualTo("Cannot parse not-a-number; at path $");
}
}

View File

@ -1,7 +1,6 @@
package com.google.gson;
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 com.google.gson.stream.JsonReader;
@ -23,8 +22,8 @@ public class TypeAdapterTest {
}
}.nullSafe();
assertEquals("null", adapter.toJson(null));
assertNull(adapter.fromJson("null"));
assertThat(adapter.toJson(null)).isEqualTo("null");
assertThat(adapter.fromJson("null")).isNull();
}
/**
@ -39,7 +38,7 @@ public class TypeAdapterTest {
throw exception;
}
@Override public Integer read(JsonReader in) throws IOException {
@Override public Integer read(JsonReader in) {
throw new AssertionError("not needed by this test");
}
};
@ -48,14 +47,14 @@ public class TypeAdapterTest {
adapter.toJson(1);
fail();
} catch (JsonIOException e) {
assertEquals(exception, e.getCause());
assertThat(e.getCause()).isEqualTo(exception);
}
try {
adapter.toJsonTree(1);
fail();
} catch (JsonIOException e) {
assertEquals(exception, e.getCause());
assertThat(e.getCause()).isEqualTo(exception);
}
}
@ -73,13 +72,13 @@ public class TypeAdapterTest {
// whether that behavior is actually desired
@Test
public void testFromJson_Reader_TrailingData() throws IOException {
assertEquals("a", adapter.fromJson(new StringReader("\"a\"1")));
assertThat(adapter.fromJson(new StringReader("\"a\"1"))).isEqualTo("a");
}
// Note: This test just verifies the current behavior; it is a bit questionable
// whether that behavior is actually desired
@Test
public void testFromJson_String_TrailingData() throws IOException {
assertEquals("a", adapter.fromJson("\"a\"1"));
assertThat(adapter.fromJson("\"a\"1")).isEqualTo("a");
}
}

View File

@ -16,8 +16,7 @@
package com.google.gson;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static com.google.common.truth.Truth.assertThat;
import com.google.gson.annotations.Since;
import com.google.gson.annotations.Until;
@ -35,41 +34,41 @@ public class VersionExclusionStrategyTest {
@Test
public void testSameVersion() throws Exception {
Excluder excluder = Excluder.DEFAULT.withVersion(VERSION);
assertFalse(excluder.excludeClass(MockClassSince.class, true));
assertFalse(excluder.excludeField(MockClassSince.class.getField("someField"), true));
assertThat(excluder.excludeClass(MockClassSince.class, true)).isFalse();
assertThat(excluder.excludeField(MockClassSince.class.getField("someField"), true)).isFalse();
// Until version is exclusive
assertTrue(excluder.excludeClass(MockClassUntil.class, true));
assertTrue(excluder.excludeField(MockClassUntil.class.getField("someField"), true));
assertThat(excluder.excludeClass(MockClassUntil.class, true)).isTrue();
assertThat(excluder.excludeField(MockClassUntil.class.getField("someField"), true)).isTrue();
assertFalse(excluder.excludeClass(MockClassBoth.class, true));
assertFalse(excluder.excludeField(MockClassBoth.class.getField("someField"), true));
assertThat(excluder.excludeClass(MockClassBoth.class, true)).isFalse();
assertThat(excluder.excludeField(MockClassBoth.class.getField("someField"), true)).isFalse();
}
@Test
public void testNewerVersion() throws Exception {
Excluder excluder = Excluder.DEFAULT.withVersion(VERSION + 5);
assertFalse(excluder.excludeClass(MockClassSince.class, true));
assertFalse(excluder.excludeField(MockClassSince.class.getField("someField"), true));
assertThat(excluder.excludeClass(MockClassSince.class, true)).isFalse();
assertThat(excluder.excludeField(MockClassSince.class.getField("someField"), true)).isFalse();
assertTrue(excluder.excludeClass(MockClassUntil.class, true));
assertTrue(excluder.excludeField(MockClassUntil.class.getField("someField"), true));
assertThat(excluder.excludeClass(MockClassUntil.class, true)).isTrue();
assertThat(excluder.excludeField(MockClassUntil.class.getField("someField"), true)).isTrue();
assertTrue(excluder.excludeClass(MockClassBoth.class, true));
assertTrue(excluder.excludeField(MockClassBoth.class.getField("someField"), true));
assertThat(excluder.excludeClass(MockClassBoth.class, true)).isTrue();
assertThat(excluder.excludeField(MockClassBoth.class.getField("someField"), true)).isTrue();
}
@Test
public void testOlderVersion() throws Exception {
Excluder excluder = Excluder.DEFAULT.withVersion(VERSION - 5);
assertTrue(excluder.excludeClass(MockClassSince.class, true));
assertTrue(excluder.excludeField(MockClassSince.class.getField("someField"), true));
assertThat(excluder.excludeClass(MockClassSince.class, true)).isTrue();
assertThat(excluder.excludeField(MockClassSince.class.getField("someField"), true)).isTrue();
assertFalse(excluder.excludeClass(MockClassUntil.class, true));
assertFalse(excluder.excludeField(MockClassUntil.class.getField("someField"), true));
assertThat(excluder.excludeClass(MockClassUntil.class, true)).isFalse();
assertThat(excluder.excludeField(MockClassUntil.class.getField("someField"), true)).isFalse();
assertTrue(excluder.excludeClass(MockClassBoth.class, true));
assertTrue(excluder.excludeField(MockClassBoth.class.getField("someField"), true));
assertThat(excluder.excludeClass(MockClassBoth.class, true)).isTrue();
assertThat(excluder.excludeField(MockClassBoth.class.getField("someField"), true)).isTrue();
}
@Since(VERSION)