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> <artifactId>junit</artifactId>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>com.google.truth</groupId>
<artifactId>truth</artifactId>
<version>1.1.3</version>
<scope>test</scope>
</dependency>
</dependencies> </dependencies>
<build> <build>

View File

@ -16,10 +16,9 @@
package com.google.gson; 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 com.google.gson.reflect.TypeToken;
import java.util.Arrays;
import java.util.List; import java.util.List;
import org.junit.Test; import org.junit.Test;
@ -43,6 +42,6 @@ public final class CommentsTest {
+ "]"; + "]";
List<String> abc = new Gson().fromJson(json, new TypeToken<List<String>>() {}.getType()); 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; package com.google.gson;
import static org.junit.Assert.assertEquals; import static com.google.common.truth.Truth.assertThat;
import java.net.InetAddress; import java.net.InetAddress;
import org.junit.Before; import org.junit.Before;
@ -39,9 +39,9 @@ public class DefaultInetAddressTypeAdapterTest {
public void testInetAddressSerializationAndDeserialization() throws Exception { public void testInetAddressSerializationAndDeserialization() throws Exception {
InetAddress address = InetAddress.getByName("8.8.8.8"); InetAddress address = InetAddress.getByName("8.8.8.8");
String jsonAddress = gson.toJson(address); 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); InetAddress value = gson.fromJson(jsonAddress, InetAddress.class);
assertEquals(value, address); assertThat(address).isEqualTo(value);
} }
} }

View File

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

View File

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

View File

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

View File

@ -1,7 +1,8 @@
package com.google.gson; package com.google.gson;
import static org.junit.Assert.assertEquals; import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertNotEquals; import static com.google.common.truth.Truth.assertWithMessage;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.util.Locale; import java.util.Locale;
import org.junit.Test; import org.junit.Test;
@ -28,7 +29,7 @@ public class FieldNamingPolicyTest {
}; };
for (String[] pair : argumentPairs) { 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) { 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 @Test
public void testUpperCasingLocaleIndependent() throws Exception { public void testUpperCasingLocaleIndependent() throws Exception {
@ -81,11 +82,13 @@ public class FieldNamingPolicyTest {
try { try {
// Verify that default Locale has different case conversion rules // 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) { for (FieldNamingPolicy policy : policies) {
// Should ignore default Locale // 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 { } finally {
Locale.setDefault(oldLocale); Locale.setDefault(oldLocale);
@ -118,11 +121,13 @@ public class FieldNamingPolicyTest {
try { try {
// Verify that default Locale has different case conversion rules // 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) { for (FieldNamingPolicy policy : policies) {
// Should ignore default Locale // 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 { } finally {
Locale.setDefault(oldLocale); Locale.setDefault(oldLocale);

View File

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

View File

@ -16,9 +16,7 @@
package com.google.gson; package com.google.gson;
import static org.junit.Assert.assertEquals; import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonReader;
@ -48,8 +46,8 @@ public class GsonBuilderTest {
public void testCreatingMoreThanOnce() { public void testCreatingMoreThanOnce() {
GsonBuilder builder = new GsonBuilder(); GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create(); Gson gson = builder.create();
assertNotNull(gson); assertThat(gson).isNotNull();
assertNotNull(builder.create()); assertThat(builder.create()).isNotNull();
builder.setFieldNamingStrategy(new FieldNamingStrategy() { builder.setFieldNamingStrategy(new FieldNamingStrategy() {
@Override public String translateName(Field f) { @Override public String translateName(Field f) {
@ -58,9 +56,9 @@ public class GsonBuilderTest {
}); });
Gson otherGson = builder.create(); Gson otherGson = builder.create();
assertNotNull(otherGson); assertThat(otherGson).isNotNull();
// Should be different instances because builder has been modified in the meantime // 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 // Modifications of `gsonBuilder` should not affect `gson` object
gsonBuilder.registerTypeAdapter(CustomClass1.class, new TypeAdapter<CustomClass1>() { gsonBuilder.registerTypeAdapter(CustomClass1.class, new TypeAdapter<CustomClass1>() {
@Override public CustomClass1 read(JsonReader in) throws IOException { @Override public CustomClass1 read(JsonReader in) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
@ -93,6 +91,7 @@ public class GsonBuilderTest {
} }
}); });
assertDefaultGson(gson); assertDefaultGson(gson);
// New GsonBuilder created from `gson` should not have been affected by changes // New GsonBuilder created from `gson` should not have been affected by changes
// to `gsonBuilder` either // to `gsonBuilder` either
@ -105,26 +104,26 @@ public class GsonBuilderTest {
private static void assertDefaultGson(Gson gson) { private static void assertDefaultGson(Gson gson) {
// Should use default reflective adapter // Should use default reflective adapter
String json1 = gson.toJson(new CustomClass1()); String json1 = gson.toJson(new CustomClass1());
assertEquals("{}", json1); assertThat(json1).isEqualTo("{}");
// Should use default reflective adapter // Should use default reflective adapter
String json2 = gson.toJson(new CustomClass2()); String json2 = gson.toJson(new CustomClass2());
assertEquals("{}", json2); assertThat(json2).isEqualTo("{}");
// Should use default instance creator // Should use default instance creator
CustomClass3 customClass3 = gson.fromJson("{}", CustomClass3.class); 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) { private static void assertCustomGson(Gson gson) {
String json1 = gson.toJson(new CustomClass1()); String json1 = gson.toJson(new CustomClass1());
assertEquals("\"custom-adapter\"", json1); assertThat(json1).isEqualTo("\"custom-adapter\"");
String json2 = gson.toJson(new CustomClass2()); String json2 = gson.toJson(new CustomClass2());
assertEquals("\"custom-hierarchy-adapter\"", json2); assertThat(json2).isEqualTo("\"custom-hierarchy-adapter\"");
CustomClass3 customClass3 = gson.fromJson("{}", CustomClass3.class); CustomClass3 customClass3 = gson.fromJson("{}", CustomClass3.class);
assertEquals("custom-instance", customClass3.s); assertThat(customClass3.s).isEqualTo("custom-instance");
} }
static class CustomClass1 { } static class CustomClass1 { }
@ -148,7 +147,7 @@ public class GsonBuilderTest {
Gson gson = new GsonBuilder() Gson gson = new GsonBuilder()
.excludeFieldsWithModifiers(Modifier.VOLATILE, Modifier.PRIVATE) .excludeFieldsWithModifiers(Modifier.VOLATILE, Modifier.PRIVATE)
.create(); .create();
assertEquals("{\"d\":\"d\"}", gson.toJson(new HasModifiers())); assertThat(gson.toJson(new HasModifiers())).isEqualTo("{\"d\":\"d\"}");
} }
@SuppressWarnings("unused") @SuppressWarnings("unused")
@ -164,7 +163,7 @@ public class GsonBuilderTest {
Gson gson = new GsonBuilder() Gson gson = new GsonBuilder()
.excludeFieldsWithModifiers() .excludeFieldsWithModifiers()
.create(); .create();
assertEquals("{\"a\":\"a\"}", gson.toJson(new HasTransients())); assertThat(gson.toJson(new HasTransients())).isEqualTo("{\"a\":\"a\"}");
} }
static class HasTransients { static class HasTransients {
@ -195,12 +194,10 @@ public class GsonBuilderTest {
gson.fromJson("{}", ClassWithoutNoArgsConstructor.class); gson.fromJson("{}", ClassWithoutNoArgsConstructor.class);
fail("Expected exception"); fail("Expected exception");
} catch (JsonIOException expected) { } catch (JsonIOException expected) {
assertEquals( assertThat(expected).hasMessageThat().isEqualTo(
"Unable to create instance of class com.google.gson.GsonBuilderTest$ClassWithoutNoArgsConstructor; " "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, " + "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.", + "adding a no-args constructor, or enabling usage of JDK Unsafe may fix this problem.");
expected.getMessage()
);
} }
} }
@ -217,14 +214,14 @@ public class GsonBuilderTest {
builder.setVersion(Double.NaN); builder.setVersion(Double.NaN);
fail(); fail();
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
assertEquals("Invalid version: NaN", e.getMessage()); assertThat(e).hasMessageThat().isEqualTo("Invalid version: NaN");
} }
try { try {
builder.setVersion(-0.1); builder.setVersion(-0.1);
fail(); fail();
} catch (IllegalArgumentException e) { } 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; package com.google.gson;
import static org.junit.Assert.assertEquals; import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import com.google.gson.Gson.FutureTypeAdapter; import com.google.gson.Gson.FutureTypeAdapter;
@ -70,10 +69,10 @@ public final class GsonTest {
CUSTOM_OBJECT_TO_NUMBER_STRATEGY, CUSTOM_NUMBER_TO_NUMBER_STRATEGY, CUSTOM_OBJECT_TO_NUMBER_STRATEGY, CUSTOM_NUMBER_TO_NUMBER_STRATEGY,
Collections.<ReflectionAccessFilter>emptyList()); Collections.<ReflectionAccessFilter>emptyList());
assertEquals(CUSTOM_EXCLUDER, gson.excluder); assertThat(gson.excluder).isEqualTo(CUSTOM_EXCLUDER);
assertEquals(CUSTOM_FIELD_NAMING_STRATEGY, gson.fieldNamingStrategy()); assertThat(gson.fieldNamingStrategy()).isEqualTo(CUSTOM_FIELD_NAMING_STRATEGY);
assertEquals(true, gson.serializeNulls()); assertThat(gson.serializeNulls()).isTrue();
assertEquals(false, gson.htmlSafe()); assertThat(gson.htmlSafe()).isFalse();
} }
@Test @Test
@ -90,14 +89,14 @@ public final class GsonTest {
.registerTypeAdapter(Object.class, new TestTypeAdapter()) .registerTypeAdapter(Object.class, new TestTypeAdapter())
.create(); .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> { 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. // Test stub.
} }
@Override public Object read(JsonReader in) throws IOException { return null; } @Override public Object read(JsonReader in) { return null; }
} }
@Test @Test
@ -107,7 +106,7 @@ public final class GsonTest {
gson.getAdapter((TypeToken<?>) null); gson.getAdapter((TypeToken<?>) null);
fail(); fail();
} catch (NullPointerException e) { } 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(); .create();
TypeAdapter<?> adapter = gson.getAdapter(requestedType); TypeAdapter<?> adapter = gson.getAdapter(requestedType);
assertEquals(2, adapterInstancesCreated.get()); assertThat(adapterInstancesCreated.get()).isEqualTo(2);
assertTrue(adapter instanceof DummyAdapter); assertThat(adapter).isInstanceOf(DummyAdapter.class);
assertTrue(threadAdapter.get() instanceof DummyAdapter); assertThat(threadAdapter.get()).isInstanceOf(DummyAdapter.class);
} }
/** /**
@ -239,7 +238,7 @@ public final class GsonTest {
} }
else if (raw == CustomClass2.class) { else if (raw == CustomClass2.class) {
TypeAdapter<?> adapter = gson.getAdapter(CustomClass1.class); TypeAdapter<?> adapter = gson.getAdapter(CustomClass1.class);
assertTrue(adapter instanceof FutureTypeAdapter); assertThat(adapter).isInstanceOf(FutureTypeAdapter.class);
return new WrappingAdapter<>(adapter); return new WrappingAdapter<>(adapter);
} }
else { else {
@ -262,12 +261,12 @@ public final class GsonTest {
isThreadWaiting.await(); isThreadWaiting.await();
TypeAdapter<?> adapter = gson.getAdapter(CustomClass1.class); TypeAdapter<?> adapter = gson.getAdapter(CustomClass1.class);
// Should not fail due to referring to unresolved FutureTypeAdapter // 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 // Let other thread proceed and have it resolve its FutureTypeAdapter
canThreadProceed.countDown(); canThreadProceed.countDown();
thread.join(); thread.join();
assertEquals("[[\"wrapped-nested\"]]", otherThreadAdapter.get().toJson(null)); assertThat(otherThreadAdapter.get().toJson(null)).isEqualTo("[[\"wrapped-nested\"]]");
} }
@Test @Test
@ -286,11 +285,11 @@ public final class GsonTest {
jsonWriter.value(1); jsonWriter.value(1);
fail(); fail();
} catch (IllegalStateException expected) { } 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(); jsonWriter.close();
assertEquals("{\"\\u003ctest2\":true}", writer.toString()); assertThat(writer.toString()).isEqualTo("{\"\\u003ctest2\":true}");
} }
@Test @Test
@ -315,7 +314,7 @@ public final class GsonTest {
jsonWriter.value(1); jsonWriter.value(1);
jsonWriter.close(); 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 @Test
@ -337,7 +336,7 @@ public final class GsonTest {
.setLenient() .setLenient()
.create() .create()
.newJsonReader(new StringReader(json)); .newJsonReader(new StringReader(json));
assertEquals("test", jsonReader.nextString()); assertThat(jsonReader.nextString()).isEqualTo("test");
jsonReader.close(); jsonReader.close();
} }
@ -382,15 +381,15 @@ public final class GsonTest {
private static void assertDefaultGson(Gson gson) { private static void assertDefaultGson(Gson gson) {
// Should use default reflective adapter // Should use default reflective adapter
String json1 = gson.toJson(new CustomClass1()); String json1 = gson.toJson(new CustomClass1());
assertEquals("{}", json1); assertThat(json1).isEqualTo("{}");
// Should use default reflective adapter // Should use default reflective adapter
String json2 = gson.toJson(new CustomClass2()); String json2 = gson.toJson(new CustomClass2());
assertEquals("{}", json2); assertThat(json2).isEqualTo("{}");
// Should use default instance creator // Should use default instance creator
CustomClass3 customClass3 = gson.fromJson("{}", CustomClass3.class); 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 // But new Gson instance from `gsonBuilder` should be affected by changes
Gson otherGson = gsonBuilder.create(); Gson otherGson = gsonBuilder.create();
String json1 = otherGson.toJson(new CustomClass1()); String json1 = otherGson.toJson(new CustomClass1());
assertEquals("\"overwritten custom-adapter\"", json1); assertThat(json1).isEqualTo("\"overwritten custom-adapter\"");
String json2 = otherGson.toJson(new CustomClass2()); 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); 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) { private static void assertCustomGson(Gson gson) {
String json1 = gson.toJson(new CustomClass1()); String json1 = gson.toJson(new CustomClass1());
assertEquals("\"custom-adapter\"", json1); assertThat(json1).isEqualTo("\"custom-adapter\"");
String json2 = gson.toJson(new CustomClass2()); String json2 = gson.toJson(new CustomClass2());
assertEquals("\"custom-hierarchy-adapter\"", json2); assertThat(json2).isEqualTo("\"custom-hierarchy-adapter\"");
CustomClass3 customClass3 = gson.fromJson("{}", CustomClass3.class); CustomClass3 customClass3 = gson.fromJson("{}", CustomClass3.class);
assertEquals("custom-instance", customClass3.s); assertThat(customClass3.s).isEqualTo("custom-instance");
} }
private static class CustomClass1 { } private static class CustomClass1 { }

View File

@ -16,8 +16,7 @@
package com.google.gson; package com.google.gson;
import static org.junit.Assert.assertEquals; import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import java.lang.reflect.Type; import java.lang.reflect.Type;
@ -60,7 +59,7 @@ public class GsonTypeAdapterTest {
} catch (IllegalStateException expected) { } } catch (IllegalStateException expected) { }
// Verify that serializer is made null-safe, i.e. it is not called for null // 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 { try {
gson.fromJson("123", AtomicLong.class); gson.fromJson("123", AtomicLong.class);
@ -68,28 +67,28 @@ public class GsonTypeAdapterTest {
} catch (JsonParseException expected) { } } catch (JsonParseException expected) { }
// Verify that deserializer is made null-safe, i.e. it is not called for null // 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 @Test
public void testTypeAdapterProperlyConvertsTypes() throws Exception { public void testTypeAdapterProperlyConvertsTypes() {
int intialValue = 1; int intialValue = 1;
AtomicInteger atomicInt = new AtomicInteger(intialValue); AtomicInteger atomicInt = new AtomicInteger(intialValue);
String json = gson.toJson(atomicInt); String json = gson.toJson(atomicInt);
assertEquals(intialValue + 1, Integer.parseInt(json)); assertThat(Integer.parseInt(json)).isEqualTo(intialValue + 1);
atomicInt = gson.fromJson(json, AtomicInteger.class); atomicInt = gson.fromJson(json, AtomicInteger.class);
assertEquals(intialValue, atomicInt.get()); assertThat(atomicInt.get()).isEqualTo(intialValue);
} }
@Test @Test
public void testTypeAdapterDoesNotAffectNonAdaptedTypes() throws Exception { public void testTypeAdapterDoesNotAffectNonAdaptedTypes() {
String expected = "blah"; String expected = "blah";
String actual = gson.toJson(expected); String actual = gson.toJson(expected);
assertEquals("\"" + expected + "\"", actual); assertThat(actual).isEqualTo("\"" + expected + "\"");
actual = gson.fromJson(actual, String.class); actual = gson.fromJson(actual, String.class);
assertEquals(expected, actual); assertThat(actual).isEqualTo(expected);
} }
private static class ExceptionTypeAdapter private static class ExceptionTypeAdapter
@ -158,6 +157,6 @@ public class GsonTypeAdapterTest {
builder.registerTypeHierarchyAdapter(Abstract.class, deserializer); builder.registerTypeHierarchyAdapter(Abstract.class, deserializer);
} }
Gson gson = builder.create(); 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; package com.google.gson;
import static org.junit.Assert.assertFalse; import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertTrue;
import com.google.gson.internal.Excluder; import com.google.gson.internal.Excluder;
import java.lang.reflect.Field; import java.lang.reflect.Field;
@ -34,27 +33,27 @@ public class InnerClassExclusionStrategyTest {
private Excluder excluder = Excluder.DEFAULT.disableInnerClassSerialization(); private Excluder excluder = Excluder.DEFAULT.disableInnerClassSerialization();
@Test @Test
public void testExcludeInnerClassObject() throws Exception { public void testExcludeInnerClassObject() {
Class<?> clazz = innerClass.getClass(); Class<?> clazz = innerClass.getClass();
assertTrue(excluder.excludeClass(clazz, true)); assertThat(excluder.excludeClass(clazz, true)).isTrue();
} }
@Test @Test
public void testExcludeInnerClassField() throws Exception { public void testExcludeInnerClassField() throws Exception {
Field f = getClass().getField("innerClass"); Field f = getClass().getField("innerClass");
assertTrue(excluder.excludeField(f, true)); assertThat(excluder.excludeField(f, true)).isTrue();
} }
@Test @Test
public void testIncludeStaticNestedClassObject() throws Exception { public void testIncludeStaticNestedClassObject() {
Class<?> clazz = staticNestedClass.getClass(); Class<?> clazz = staticNestedClass.getClass();
assertFalse(excluder.excludeClass(clazz, true)); assertThat(excluder.excludeClass(clazz, true)).isFalse();
} }
@Test @Test
public void testIncludeStaticNestedClassField() throws Exception { public void testIncludeStaticNestedClassField() throws Exception {
Field f = getClass().getField("staticNestedClass"); Field f = getClass().getField("staticNestedClass");
assertFalse(excluder.excludeField(f, true)); assertThat(excluder.excludeField(f, true)).isFalse();
} }
class InnerClass { class InnerClass {

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,8 +1,7 @@
package com.google.gson; 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 java.util.Arrays;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
@ -31,11 +30,11 @@ public class JsonParserParameterizedTest {
public String json; public String json;
@Test @Test
public void testParse() throws IOException { public void testParse() {
JsonElement deserialized = JsonParser.parseString(json); JsonElement deserialized = JsonParser.parseString(json);
String actualSerialized = adapter.toJson(deserialized); String actualSerialized = adapter.toJson(deserialized);
// Serialized JsonElement should be the same as original JSON // 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; package com.google.gson;
import static org.junit.Assert.assertEquals; import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import com.google.gson.common.TestTypes.BagOfPrimitives; import com.google.gson.common.TestTypes.BagOfPrimitives;
@ -47,37 +46,37 @@ public class JsonParserTest {
@Test @Test
public void testParseUnquotedStringArrayFails() { public void testParseUnquotedStringArrayFails() {
JsonElement element = JsonParser.parseString("[a,b,c]"); JsonElement element = JsonParser.parseString("[a,b,c]");
assertEquals("a", element.getAsJsonArray().get(0).getAsString()); assertThat(element.getAsJsonArray().get(0).getAsString()).isEqualTo("a");
assertEquals("b", element.getAsJsonArray().get(1).getAsString()); assertThat(element.getAsJsonArray().get(1).getAsString()).isEqualTo("b");
assertEquals("c", element.getAsJsonArray().get(2).getAsString()); assertThat(element.getAsJsonArray().get(2).getAsString()).isEqualTo("c");
assertEquals(3, element.getAsJsonArray().size()); assertThat(element.getAsJsonArray()).hasSize(3);
} }
@Test @Test
public void testParseString() { public void testParseString() {
String json = "{a:10,b:'c'}"; String json = "{a:10,b:'c'}";
JsonElement e = JsonParser.parseString(json); JsonElement e = JsonParser.parseString(json);
assertTrue(e.isJsonObject()); assertThat(e.isJsonObject()).isTrue();
assertEquals(10, e.getAsJsonObject().get("a").getAsInt()); assertThat(e.getAsJsonObject().get("a").getAsInt()).isEqualTo(10);
assertEquals("c", e.getAsJsonObject().get("b").getAsString()); assertThat(e.getAsJsonObject().get("b").getAsString()).isEqualTo("c");
} }
@Test @Test
public void testParseEmptyString() { public void testParseEmptyString() {
JsonElement e = JsonParser.parseString("\" \""); JsonElement e = JsonParser.parseString("\" \"");
assertTrue(e.isJsonPrimitive()); assertThat(e.isJsonPrimitive()).isTrue();
assertEquals(" ", e.getAsString()); assertThat(e.getAsString()).isEqualTo(" ");
} }
@Test @Test
public void testParseEmptyWhitespaceInput() { public void testParseEmptyWhitespaceInput() {
JsonElement e = JsonParser.parseString(" "); JsonElement e = JsonParser.parseString(" ");
assertTrue(e.isJsonNull()); assertThat(e.isJsonNull()).isTrue();
} }
@Test @Test
public void testParseUnquotedSingleWordStringFails() { public void testParseUnquotedSingleWordStringFails() {
assertEquals("Test", JsonParser.parseString("Test").getAsString()); assertThat(JsonParser.parseString("Test").getAsString()).isEqualTo("Test");
} }
@Test @Test
@ -93,12 +92,12 @@ public class JsonParserTest {
public void testParseMixedArray() { public void testParseMixedArray() {
String json = "[{},13,\"stringValue\"]"; String json = "[{},13,\"stringValue\"]";
JsonElement e = JsonParser.parseString(json); JsonElement e = JsonParser.parseString(json);
assertTrue(e.isJsonArray()); assertThat(e.isJsonArray()).isTrue();
JsonArray array = e.getAsJsonArray(); JsonArray array = e.getAsJsonArray();
assertEquals("{}", array.get(0).toString()); assertThat(array.get(0).toString()).isEqualTo("{}");
assertEquals(13, array.get(1).getAsInt()); assertThat(array.get(1).getAsInt()).isEqualTo(13);
assertEquals("stringValue", array.get(2).getAsString()); assertThat(array.get(2).getAsString()).isEqualTo("stringValue");
} }
private static String repeat(String s, int times) { private static String repeat(String s, int times) {
@ -123,10 +122,10 @@ public class JsonParserTest {
if (current.isEmpty()) { if (current.isEmpty()) {
break; break;
} }
assertEquals(1, current.size()); assertThat(current.size()).isEqualTo(1);
current = current.get(0).getAsJsonArray(); current = current.get(0).getAsJsonArray();
} }
assertEquals(times, actualTimes); assertThat(actualTimes).isEqualTo(times);
} }
/** Deeply nested JSON objects should not cause {@link StackOverflowError} */ /** Deeply nested JSON objects should not cause {@link StackOverflowError} */
@ -139,7 +138,7 @@ public class JsonParserTest {
int actualTimes = 0; int actualTimes = 0;
JsonObject current = JsonParser.parseString(json).getAsJsonObject(); JsonObject current = JsonParser.parseString(json).getAsJsonObject();
while (true) { while (true) {
assertEquals(1, current.size()); assertThat(current.size()).isEqualTo(1);
actualTimes++; actualTimes++;
JsonElement next = current.get("a"); JsonElement next = current.get("a");
if (next.isJsonNull()) { if (next.isJsonNull()) {
@ -148,16 +147,16 @@ public class JsonParserTest {
current = next.getAsJsonObject(); current = next.getAsJsonObject();
} }
} }
assertEquals(times, actualTimes); assertThat(actualTimes).isEqualTo(times);
} }
@Test @Test
public void testParseReader() { public void testParseReader() {
StringReader reader = new StringReader("{a:10,b:'c'}"); StringReader reader = new StringReader("{a:10,b:'c'}");
JsonElement e = JsonParser.parseReader(reader); JsonElement e = JsonParser.parseReader(reader);
assertTrue(e.isJsonObject()); assertThat(e.isJsonObject()).isTrue();
assertEquals(10, e.getAsJsonObject().get("a").getAsInt()); assertThat(e.getAsJsonObject().get("a").getAsInt()).isEqualTo(10);
assertEquals("c", e.getAsJsonObject().get("b").getAsString()); assertThat(e.getAsJsonObject().get("b").getAsString()).isEqualTo("c");
} }
@Test @Test
@ -175,8 +174,8 @@ public class JsonParserTest {
JsonElement element1 = Streams.parse(parser); JsonElement element1 = Streams.parse(parser);
JsonElement element2 = Streams.parse(parser); JsonElement element2 = Streams.parse(parser);
BagOfPrimitives actualOne = gson.fromJson(element1, BagOfPrimitives.class); BagOfPrimitives actualOne = gson.fromJson(element1, BagOfPrimitives.class);
assertEquals("one", actualOne.stringValue); assertThat(actualOne.stringValue).isEqualTo("one");
BagOfPrimitives actualTwo = gson.fromJson(element2, BagOfPrimitives.class); 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; package com.google.gson;
import static org.junit.Assert.assertEquals; import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertFalse; import static com.google.common.truth.Truth.assertWithMessage;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import com.google.gson.common.MoreAsserts; import com.google.gson.common.MoreAsserts;
@ -60,50 +58,50 @@ public class JsonPrimitiveTest {
} }
@Test @Test
public void testBoolean() throws Exception { public void testBoolean() {
JsonPrimitive json = new JsonPrimitive(Boolean.TRUE); JsonPrimitive json = new JsonPrimitive(Boolean.TRUE);
assertTrue(json.isBoolean()); assertThat(json.isBoolean()).isTrue();
assertTrue(json.getAsBoolean()); assertThat(json.getAsBoolean()).isTrue();
// Extra support for booleans // Extra support for booleans
json = new JsonPrimitive(1); json = new JsonPrimitive(1);
assertFalse(json.getAsBoolean()); assertThat(json.getAsBoolean()).isFalse();
json = new JsonPrimitive("1"); json = new JsonPrimitive("1");
assertFalse(json.getAsBoolean()); assertThat(json.getAsBoolean()).isFalse();
json = new JsonPrimitive("true"); json = new JsonPrimitive("true");
assertTrue(json.getAsBoolean()); assertThat(json.getAsBoolean()).isTrue();
json = new JsonPrimitive("TrUe"); json = new JsonPrimitive("TrUe");
assertTrue(json.getAsBoolean()); assertThat(json.getAsBoolean()).isTrue();
json = new JsonPrimitive("1.3"); json = new JsonPrimitive("1.3");
assertFalse(json.getAsBoolean()); assertThat(json.getAsBoolean()).isFalse();
} }
@Test @Test
public void testParsingStringAsBoolean() throws Exception { public void testParsingStringAsBoolean() {
JsonPrimitive json = new JsonPrimitive("true"); JsonPrimitive json = new JsonPrimitive("true");
assertFalse(json.isBoolean()); assertThat(json.isBoolean()).isFalse();
assertTrue(json.getAsBoolean()); assertThat(json.getAsBoolean()).isTrue();
} }
@Test @Test
public void testParsingStringAsNumber() throws Exception { public void testParsingStringAsNumber() {
JsonPrimitive json = new JsonPrimitive("1"); JsonPrimitive json = new JsonPrimitive("1");
assertFalse(json.isNumber()); assertThat(json.isNumber()).isFalse();
assertEquals(1D, json.getAsDouble(), 0.00001); assertThat(json.getAsDouble()).isEqualTo(1.0);
assertEquals(1F, json.getAsFloat(), 0.00001); assertThat(json.getAsFloat()).isEqualTo(1F);
assertEquals(1, json.getAsInt()); assertThat(json.getAsInt()).isEqualTo(1);
assertEquals(1L, json.getAsLong()); assertThat(json.getAsLong()).isEqualTo(1L);
assertEquals((short) 1, json.getAsShort()); assertThat(json.getAsShort()).isEqualTo((short) 1);
assertEquals((byte) 1, json.getAsByte()); assertThat(json.getAsByte()).isEqualTo((byte) 1);
assertEquals(new BigInteger("1"), json.getAsBigInteger()); assertThat(json.getAsBigInteger()).isEqualTo(new BigInteger("1"));
assertEquals(new BigDecimal("1"), json.getAsBigDecimal()); assertThat(json.getAsBigDecimal()).isEqualTo(new BigDecimal("1"));
} }
@Test @Test
@ -113,43 +111,42 @@ public class JsonPrimitiveTest {
json.getAsNumber(); json.getAsNumber();
fail(); fail();
} catch (UnsupportedOperationException e) { } 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") @SuppressWarnings("deprecation")
@Test @Test
public void testStringsAndChar() throws Exception { public void testStringsAndChar() {
JsonPrimitive json = new JsonPrimitive("abc"); JsonPrimitive json = new JsonPrimitive("abc");
assertTrue(json.isString()); assertThat(json.isString()).isTrue();
assertEquals('a', json.getAsCharacter()); assertThat(json.getAsCharacter()).isEqualTo('a');
assertEquals("abc", json.getAsString()); assertThat(json.getAsString()).isEqualTo("abc");
json = new JsonPrimitive('z'); json = new JsonPrimitive('z');
assertTrue(json.isString()); assertThat(json.isString()).isTrue();
assertEquals('z', json.getAsCharacter()); assertThat(json.getAsCharacter()).isEqualTo('z');
assertEquals("z", json.getAsString()); assertThat(json.getAsString()).isEqualTo("z");
json = new JsonPrimitive(true); json = new JsonPrimitive(true);
assertEquals("true", json.getAsString()); assertThat(json.getAsString()).isEqualTo("true");
json = new JsonPrimitive(""); json = new JsonPrimitive("");
assertEquals("", json.getAsString()); assertThat(json.getAsString()).isEqualTo("");
try { try {
json.getAsCharacter(); json.getAsCharacter();
fail(); fail();
} catch (UnsupportedOperationException e) { } catch (UnsupportedOperationException e) {
assertEquals("String value is empty", e.getMessage()); assertThat(e).hasMessageThat().isEqualTo("String value is empty");
} }
} }
@Test @Test
public void testExponential() throws Exception { public void testExponential() {
JsonPrimitive json = new JsonPrimitive("1E+7"); JsonPrimitive json = new JsonPrimitive("1E+7");
assertEquals(new BigDecimal("1E+7"), json.getAsBigDecimal()); assertThat(json.getAsBigDecimal()).isEqualTo(new BigDecimal("1E+7"));
assertEquals(1E+7, json.getAsDouble(), 0.00001); assertThat(json.getAsDouble()).isEqualTo(1E+7);
assertEquals(1E+7, json.getAsDouble(), 0.00001);
try { try {
json.getAsInt(); json.getAsInt();
@ -159,115 +156,115 @@ public class JsonPrimitiveTest {
@Test @Test
public void testByteEqualsShort() { public void testByteEqualsShort() {
JsonPrimitive p1 = new JsonPrimitive(Byte.valueOf((byte)10)); JsonPrimitive p1 = new JsonPrimitive((byte) 10);
JsonPrimitive p2 = new JsonPrimitive(Short.valueOf((short)10)); JsonPrimitive p2 = new JsonPrimitive((short) 10);
assertEquals(p1, p2); assertThat(p1).isEqualTo(p2);
assertEquals(p1.hashCode(), p2.hashCode()); assertThat(p1.hashCode()).isEqualTo(p2.hashCode());
} }
@Test @Test
public void testByteEqualsInteger() { public void testByteEqualsInteger() {
JsonPrimitive p1 = new JsonPrimitive(Byte.valueOf((byte)10)); JsonPrimitive p1 = new JsonPrimitive((byte) 10);
JsonPrimitive p2 = new JsonPrimitive(Integer.valueOf(10)); JsonPrimitive p2 = new JsonPrimitive(10);
assertEquals(p1, p2); assertThat(p1).isEqualTo(p2);
assertEquals(p1.hashCode(), p2.hashCode()); assertThat(p1.hashCode()).isEqualTo(p2.hashCode());
} }
@Test @Test
public void testByteEqualsLong() { public void testByteEqualsLong() {
JsonPrimitive p1 = new JsonPrimitive(Byte.valueOf((byte)10)); JsonPrimitive p1 = new JsonPrimitive((byte) 10);
JsonPrimitive p2 = new JsonPrimitive(Long.valueOf(10L)); JsonPrimitive p2 = new JsonPrimitive(10L);
assertEquals(p1, p2); assertThat(p1).isEqualTo(p2);
assertEquals(p1.hashCode(), p2.hashCode()); assertThat(p1.hashCode()).isEqualTo(p2.hashCode());
} }
@Test @Test
public void testByteEqualsBigInteger() { public void testByteEqualsBigInteger() {
JsonPrimitive p1 = new JsonPrimitive(Byte.valueOf((byte)10)); JsonPrimitive p1 = new JsonPrimitive((byte) 10);
JsonPrimitive p2 = new JsonPrimitive(new BigInteger("10")); JsonPrimitive p2 = new JsonPrimitive(new BigInteger("10"));
assertEquals(p1, p2); assertThat(p1).isEqualTo(p2);
assertEquals(p1.hashCode(), p2.hashCode()); assertThat(p1.hashCode()).isEqualTo(p2.hashCode());
} }
@Test @Test
public void testShortEqualsInteger() { public void testShortEqualsInteger() {
JsonPrimitive p1 = new JsonPrimitive(Short.valueOf((short)10)); JsonPrimitive p1 = new JsonPrimitive((short) 10);
JsonPrimitive p2 = new JsonPrimitive(Integer.valueOf(10)); JsonPrimitive p2 = new JsonPrimitive(10);
assertEquals(p1, p2); assertThat(p1).isEqualTo(p2);
assertEquals(p1.hashCode(), p2.hashCode()); assertThat(p1.hashCode()).isEqualTo(p2.hashCode());
} }
@Test @Test
public void testShortEqualsLong() { public void testShortEqualsLong() {
JsonPrimitive p1 = new JsonPrimitive(Short.valueOf((short)10)); JsonPrimitive p1 = new JsonPrimitive((short) 10);
JsonPrimitive p2 = new JsonPrimitive(Long.valueOf(10)); JsonPrimitive p2 = new JsonPrimitive(10L);
assertEquals(p1, p2); assertThat(p1).isEqualTo(p2);
assertEquals(p1.hashCode(), p2.hashCode()); assertThat(p1.hashCode()).isEqualTo(p2.hashCode());
} }
@Test @Test
public void testShortEqualsBigInteger() { public void testShortEqualsBigInteger() {
JsonPrimitive p1 = new JsonPrimitive(Short.valueOf((short)10)); JsonPrimitive p1 = new JsonPrimitive((short) 10);
JsonPrimitive p2 = new JsonPrimitive(new BigInteger("10")); JsonPrimitive p2 = new JsonPrimitive(new BigInteger("10"));
assertEquals(p1, p2); assertThat(p1).isEqualTo(p2);
assertEquals(p1.hashCode(), p2.hashCode()); assertThat(p1.hashCode()).isEqualTo(p2.hashCode());
} }
@Test @Test
public void testIntegerEqualsLong() { public void testIntegerEqualsLong() {
JsonPrimitive p1 = new JsonPrimitive(Integer.valueOf(10)); JsonPrimitive p1 = new JsonPrimitive(10);
JsonPrimitive p2 = new JsonPrimitive(Long.valueOf(10L)); JsonPrimitive p2 = new JsonPrimitive(10L);
assertEquals(p1, p2); assertThat(p1).isEqualTo(p2);
assertEquals(p1.hashCode(), p2.hashCode()); assertThat(p1.hashCode()).isEqualTo(p2.hashCode());
} }
@Test @Test
public void testIntegerEqualsBigInteger() { public void testIntegerEqualsBigInteger() {
JsonPrimitive p1 = new JsonPrimitive(Integer.valueOf(10)); JsonPrimitive p1 = new JsonPrimitive(10);
JsonPrimitive p2 = new JsonPrimitive(new BigInteger("10")); JsonPrimitive p2 = new JsonPrimitive(new BigInteger("10"));
assertEquals(p1, p2); assertThat(p1).isEqualTo(p2);
assertEquals(p1.hashCode(), p2.hashCode()); assertThat(p1.hashCode()).isEqualTo(p2.hashCode());
} }
@Test @Test
public void testLongEqualsBigInteger() { public void testLongEqualsBigInteger() {
JsonPrimitive p1 = new JsonPrimitive(Long.valueOf(10L)); JsonPrimitive p1 = new JsonPrimitive(10L);
JsonPrimitive p2 = new JsonPrimitive(new BigInteger("10")); JsonPrimitive p2 = new JsonPrimitive(new BigInteger("10"));
assertEquals(p1, p2); assertThat(p1).isEqualTo(p2);
assertEquals(p1.hashCode(), p2.hashCode()); assertThat(p1.hashCode()).isEqualTo(p2.hashCode());
} }
@Test @Test
public void testFloatEqualsDouble() { public void testFloatEqualsDouble() {
JsonPrimitive p1 = new JsonPrimitive(Float.valueOf(10.25F)); JsonPrimitive p1 = new JsonPrimitive(10.25F);
JsonPrimitive p2 = new JsonPrimitive(Double.valueOf(10.25D)); JsonPrimitive p2 = new JsonPrimitive(10.25D);
assertEquals(p1, p2); assertThat(p1).isEqualTo(p2);
assertEquals(p1.hashCode(), p2.hashCode()); assertThat(p1.hashCode()).isEqualTo(p2.hashCode());
} }
@Test @Test
public void testFloatEqualsBigDecimal() { 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")); JsonPrimitive p2 = new JsonPrimitive(new BigDecimal("10.25"));
assertEquals(p1, p2); assertThat(p1).isEqualTo(p2);
assertEquals(p1.hashCode(), p2.hashCode()); assertThat(p1.hashCode()).isEqualTo(p2.hashCode());
} }
@Test @Test
public void testDoubleEqualsBigDecimal() { 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")); JsonPrimitive p2 = new JsonPrimitive(new BigDecimal("10.25"));
assertEquals(p1, p2); assertThat(p1).isEqualTo(p2);
assertEquals(p1.hashCode(), p2.hashCode()); assertThat(p1.hashCode()).isEqualTo(p2.hashCode());
} }
@Test @Test
public void testValidJsonOnToString() throws Exception { public void testValidJsonOnToString() {
JsonPrimitive json = new JsonPrimitive("Some\nEscaped\nValue"); 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")); json = new JsonPrimitive(new BigDecimal("1.333"));
assertEquals("1.333", json.toString()); assertThat(json.toString()).isEqualTo("1.333");
} }
@Test @Test
@ -286,9 +283,9 @@ public class JsonPrimitiveTest {
new JsonPrimitive(Double.NEGATIVE_INFINITY)); new JsonPrimitive(Double.NEGATIVE_INFINITY));
MoreAsserts.assertEqualsAndHashCode(new JsonPrimitive(Double.POSITIVE_INFINITY), MoreAsserts.assertEqualsAndHashCode(new JsonPrimitive(Double.POSITIVE_INFINITY),
new JsonPrimitive(Double.POSITIVE_INFINITY)); new JsonPrimitive(Double.POSITIVE_INFINITY));
assertFalse(new JsonPrimitive("a").equals(new JsonPrimitive("b"))); assertThat(new JsonPrimitive("a").equals(new JsonPrimitive("b"))).isFalse();
assertFalse(new JsonPrimitive(true).equals(new JsonPrimitive(false))); assertThat(new JsonPrimitive(true).equals(new JsonPrimitive(false))).isFalse();
assertFalse(new JsonPrimitive(0).equals(new JsonPrimitive(1))); assertThat(new JsonPrimitive(0).equals(new JsonPrimitive(1))).isFalse();
} }
@Test @Test
@ -306,19 +303,19 @@ public class JsonPrimitiveTest {
JsonPrimitive b = new JsonPrimitive(new BigInteger("18446744073709551621")); // 2^64 + 5 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 // Ideally, the following assertion should have failed but the price is too much to pay
// assertFalse(a + " equals " + b, a.equals(b)); // 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 @Test
public void testEqualsDoesNotEquateStringAndNonStringTypes() { public void testEqualsDoesNotEquateStringAndNonStringTypes() {
assertFalse(new JsonPrimitive("true").equals(new JsonPrimitive(true))); assertThat(new JsonPrimitive("true").equals(new JsonPrimitive(true))).isFalse();
assertFalse(new JsonPrimitive("0").equals(new JsonPrimitive(0))); assertThat(new JsonPrimitive("0").equals(new JsonPrimitive(0))).isFalse();
assertFalse(new JsonPrimitive("NaN").equals(new JsonPrimitive(Float.NaN))); assertThat(new JsonPrimitive("NaN").equals(new JsonPrimitive(Float.NaN))).isFalse();
} }
@Test @Test
public void testDeepCopy() { public void testDeepCopy() {
JsonPrimitive a = new JsonPrimitive("a"); 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; package com.google.gson;
import static org.junit.Assert.assertEquals; import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import java.io.EOFException; import java.io.EOFException;
@ -41,33 +39,33 @@ public class JsonStreamParserTest {
@Test @Test
public void testParseTwoStrings() { public void testParseTwoStrings() {
String actualOne = parser.next().getAsString(); String actualOne = parser.next().getAsString();
assertEquals("one", actualOne); assertThat(actualOne).isEqualTo("one");
String actualTwo = parser.next().getAsString(); String actualTwo = parser.next().getAsString();
assertEquals("two", actualTwo); assertThat(actualTwo).isEqualTo("two");
} }
@Test @Test
public void testIterator() { public void testIterator() {
assertTrue(parser.hasNext()); assertThat(parser.hasNext()).isTrue();
assertEquals("one", parser.next().getAsString()); assertThat(parser.next().getAsString()).isEqualTo("one");
assertTrue(parser.hasNext()); assertThat(parser.hasNext()).isTrue();
assertEquals("two", parser.next().getAsString()); assertThat(parser.next().getAsString()).isEqualTo("two");
assertFalse(parser.hasNext()); assertThat(parser.hasNext()).isFalse();
} }
@Test @Test
public void testNoSideEffectForHasNext() throws Exception { public void testNoSideEffectForHasNext() {
assertTrue(parser.hasNext()); assertThat(parser.hasNext()).isTrue();
assertTrue(parser.hasNext()); assertThat(parser.hasNext()).isTrue();
assertTrue(parser.hasNext()); assertThat(parser.hasNext()).isTrue();
assertEquals("one", parser.next().getAsString()); assertThat(parser.next().getAsString()).isEqualTo("one");
assertTrue(parser.hasNext()); assertThat(parser.hasNext()).isTrue();
assertTrue(parser.hasNext()); assertThat(parser.hasNext()).isTrue();
assertEquals("two", parser.next().getAsString()); assertThat(parser.next().getAsString()).isEqualTo("two");
assertFalse(parser.hasNext()); assertThat(parser.hasNext()).isFalse();
assertFalse(parser.hasNext()); assertThat(parser.hasNext()).isFalse();
} }
@Test @Test
@ -88,7 +86,7 @@ public class JsonStreamParserTest {
parser.next(); parser.next();
fail(); fail();
} catch (JsonIOException e) { } catch (JsonIOException e) {
assertTrue(e.getCause() instanceof EOFException); assertThat(e.getCause()).isInstanceOf(EOFException.class);
} }
parser = new JsonStreamParser(""); parser = new JsonStreamParser("");
@ -96,14 +94,14 @@ public class JsonStreamParserTest {
parser.hasNext(); parser.hasNext();
fail(); fail();
} catch (JsonIOException e) { } catch (JsonIOException e) {
assertTrue(e.getCause() instanceof EOFException); assertThat(e.getCause()).isInstanceOf(EOFException.class);
} }
} }
@Test @Test
public void testIncompleteInput() { public void testIncompleteInput() {
JsonStreamParser parser = new JsonStreamParser("["); JsonStreamParser parser = new JsonStreamParser("[");
assertTrue(parser.hasNext()); assertThat(parser.hasNext()).isTrue();
try { try {
parser.next(); parser.next();
fail(); fail();

View File

@ -16,9 +16,7 @@
package com.google.gson; package com.google.gson;
import static org.junit.Assert.assertEquals; import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test; import org.junit.Test;
@ -33,12 +31,12 @@ public class LongSerializationPolicyTest {
@Test @Test
public void testDefaultLongSerialization() throws Exception { public void testDefaultLongSerialization() throws Exception {
JsonElement element = LongSerializationPolicy.DEFAULT.serialize(1556L); JsonElement element = LongSerializationPolicy.DEFAULT.serialize(1556L);
assertTrue(element.isJsonPrimitive()); assertThat(element.isJsonPrimitive()).isTrue();
JsonPrimitive jsonPrimitive = element.getAsJsonPrimitive(); JsonPrimitive jsonPrimitive = element.getAsJsonPrimitive();
assertFalse(jsonPrimitive.isString()); assertThat(jsonPrimitive.isString()).isFalse();
assertTrue(jsonPrimitive.isNumber()); assertThat(jsonPrimitive.isNumber()).isTrue();
assertEquals(1556L, element.getAsLong()); assertThat(element.getAsLong()).isEqualTo(1556L);
} }
@Test @Test
@ -46,30 +44,30 @@ public class LongSerializationPolicyTest {
Gson gson = new GsonBuilder() Gson gson = new GsonBuilder()
.setLongSerializationPolicy(LongSerializationPolicy.DEFAULT) .setLongSerializationPolicy(LongSerializationPolicy.DEFAULT)
.create(); .create();
assertEquals("[1]", gson.toJson(new long[] { 1L }, long[].class)); assertThat(gson.toJson(new long[] { 1L }, long[].class)).isEqualTo("[1]");
assertEquals("[1]", gson.toJson(new Long[] { 1L }, Long[].class)); assertThat(gson.toJson(new Long[] { 1L }, Long[].class)).isEqualTo("[1]");
} }
@Test @Test
public void testDefaultLongSerializationNull() { public void testDefaultLongSerializationNull() {
LongSerializationPolicy policy = LongSerializationPolicy.DEFAULT; LongSerializationPolicy policy = LongSerializationPolicy.DEFAULT;
assertTrue(policy.serialize(null).isJsonNull()); assertThat(policy.serialize(null).isJsonNull()).isTrue();
Gson gson = new GsonBuilder() Gson gson = new GsonBuilder()
.setLongSerializationPolicy(policy) .setLongSerializationPolicy(policy)
.create(); .create();
assertEquals("null", gson.toJson(null, Long.class)); assertThat(gson.toJson(null, Long.class)).isEqualTo("null");
} }
@Test @Test
public void testStringLongSerialization() throws Exception { public void testStringLongSerialization() throws Exception {
JsonElement element = LongSerializationPolicy.STRING.serialize(1556L); JsonElement element = LongSerializationPolicy.STRING.serialize(1556L);
assertTrue(element.isJsonPrimitive()); assertThat(element.isJsonPrimitive()).isTrue();
JsonPrimitive jsonPrimitive = element.getAsJsonPrimitive(); JsonPrimitive jsonPrimitive = element.getAsJsonPrimitive();
assertFalse(jsonPrimitive.isNumber()); assertThat(jsonPrimitive.isNumber()).isFalse();
assertTrue(jsonPrimitive.isString()); assertThat(jsonPrimitive.isString()).isTrue();
assertEquals("1556", element.getAsString()); assertThat(element.getAsString()).isEqualTo("1556");
} }
@Test @Test
@ -77,18 +75,18 @@ public class LongSerializationPolicyTest {
Gson gson = new GsonBuilder() Gson gson = new GsonBuilder()
.setLongSerializationPolicy(LongSerializationPolicy.STRING) .setLongSerializationPolicy(LongSerializationPolicy.STRING)
.create(); .create();
assertEquals("[\"1\"]", gson.toJson(new long[] { 1L }, long[].class)); assertThat(gson.toJson(new long[] { 1L }, long[].class)).isEqualTo("[\"1\"]");
assertEquals("[\"1\"]", gson.toJson(new Long[] { 1L }, Long[].class)); assertThat(gson.toJson(new Long[] { 1L }, long[].class)).isEqualTo("[\"1\"]");
} }
@Test @Test
public void testStringLongSerializationNull() { public void testStringLongSerializationNull() {
LongSerializationPolicy policy = LongSerializationPolicy.STRING; LongSerializationPolicy policy = LongSerializationPolicy.STRING;
assertTrue(policy.serialize(null).isJsonNull()); assertThat(policy.serialize(null).isJsonNull()).isTrue();
Gson gson = new GsonBuilder() Gson gson = new GsonBuilder()
.setLongSerializationPolicy(policy) .setLongSerializationPolicy(policy)
.create(); .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; package com.google.gson;
import static org.junit.Assert.assertEquals; import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import com.google.gson.reflect.TypeToken; import com.google.gson.reflect.TypeToken;
@ -65,7 +63,7 @@ public final class MixedStreamTest {
gson.toJson(RED_MIATA, Car.class, jsonWriter); gson.toJson(RED_MIATA, Car.class, jsonWriter);
jsonWriter.endArray(); jsonWriter.endArray();
assertEquals(CARS_JSON, stringWriter.toString()); assertThat(stringWriter.toString()).isEqualTo(CARS_JSON);
} }
@Test @Test
@ -75,9 +73,11 @@ public final class MixedStreamTest {
JsonReader jsonReader = new JsonReader(stringReader); JsonReader jsonReader = new JsonReader(stringReader);
jsonReader.beginArray(); jsonReader.beginArray();
assertEquals(BLUE_MUSTANG, gson.fromJson(jsonReader, Car.class)); // actual and expected object are inverted in the test.
assertEquals(BLACK_BMW, gson.fromJson(jsonReader, Car.class)); // gson.fromJson(jsonReader, Car.class) as arg of assertThat() cause an ambiguous method call
assertEquals(RED_MIATA, gson.fromJson(jsonReader, Car.class)); 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(); jsonReader.endArray();
} }
@ -89,11 +89,11 @@ public final class MixedStreamTest {
jsonReader.setLenient(false); jsonReader.setLenient(false);
gson.fromJson(jsonReader, Car.class); gson.fromJson(jsonReader, Car.class);
assertFalse(jsonReader.isLenient()); assertThat(jsonReader.isLenient()).isFalse();
jsonReader.setLenient(true); jsonReader.setLenient(true);
gson.fromJson(jsonReader, Car.class); gson.fromJson(jsonReader, Car.class);
assertTrue(jsonReader.isLenient()); assertThat(jsonReader.isLenient()).isTrue();
} }
@Test @Test
@ -105,14 +105,14 @@ public final class MixedStreamTest {
jsonWriter.setHtmlSafe(true); jsonWriter.setHtmlSafe(true);
jsonWriter.setLenient(true); jsonWriter.setLenient(true);
gson.toJson(BLUE_MUSTANG, Car.class, jsonWriter); gson.toJson(BLUE_MUSTANG, Car.class, jsonWriter);
assertTrue(jsonWriter.isHtmlSafe()); assertThat(jsonWriter.isHtmlSafe()).isTrue();
assertTrue(jsonWriter.isLenient()); assertThat(jsonWriter.isLenient()).isTrue();
jsonWriter.setHtmlSafe(false); jsonWriter.setHtmlSafe(false);
jsonWriter.setLenient(false); jsonWriter.setLenient(false);
gson.toJson(BLUE_MUSTANG, Car.class, jsonWriter); gson.toJson(BLUE_MUSTANG, Car.class, jsonWriter);
assertFalse(jsonWriter.isHtmlSafe()); assertThat(jsonWriter.isHtmlSafe()).isFalse();
assertFalse(jsonWriter.isLenient()); assertThat(jsonWriter.isLenient()).isFalse();
} }
@Test @Test
@ -177,7 +177,7 @@ public final class MixedStreamTest {
StringWriter stringWriter = new StringWriter(); StringWriter stringWriter = new StringWriter();
gson.toJson(null, new JsonWriter(stringWriter)); gson.toJson(null, new JsonWriter(stringWriter));
assertEquals("null", stringWriter.toString()); assertThat(stringWriter.toString()).isEqualTo("null");
} }
@Test @Test
@ -202,14 +202,14 @@ public final class MixedStreamTest {
StringWriter writer = new StringWriter(); StringWriter writer = new StringWriter();
new Gson().toJson(contents, type, new JsonWriter(writer)); new Gson().toJson(contents, type, new JsonWriter(writer));
assertEquals("[\"\\u003c\",\"\\u003e\",\"\\u0026\",\"\\u003d\",\"\\u0027\"]", assertThat(writer.toString())
writer.toString()); .isEqualTo("[\"\\u003c\",\"\\u003e\",\"\\u0026\",\"\\u003d\",\"\\u0027\"]");
writer = new StringWriter(); writer = new StringWriter();
new GsonBuilder().disableHtmlEscaping().create() new GsonBuilder().disableHtmlEscaping().create()
.toJson(contents, type, new JsonWriter(writer)); .toJson(contents, type, new JsonWriter(writer));
assertEquals("[\"<\",\">\",\"&\",\"=\",\"'\"]", assertThat(writer.toString())
writer.toString()); .isEqualTo("[\"<\",\">\",\"&\",\"=\",\"'\"]");
} }
@Test @Test
@ -222,7 +222,7 @@ public final class MixedStreamTest {
JsonWriter jsonWriter = new JsonWriter(writer); JsonWriter jsonWriter = new JsonWriter(writer);
new GsonBuilder().serializeSpecialFloatingPointValues().create() new GsonBuilder().serializeSpecialFloatingPointValues().create()
.toJson(doubles, type, jsonWriter); .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 { try {
new Gson().toJson(doubles, type, new JsonWriter(new StringWriter())); new Gson().toJson(doubles, type, new JsonWriter(new StringWriter()));

View File

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

View File

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

View File

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

View File

@ -16,7 +16,7 @@
package com.google.gson; 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 static org.junit.Assert.fail;
import com.google.gson.internal.LazilyParsedNumber; import com.google.gson.internal.LazilyParsedNumber;
@ -31,13 +31,13 @@ public class ToNumberPolicyTest {
@Test @Test
public void testDouble() throws IOException { public void testDouble() throws IOException {
ToNumberStrategy strategy = ToNumberPolicy.DOUBLE; ToNumberStrategy strategy = ToNumberPolicy.DOUBLE;
assertEquals(10.1, strategy.readNumber(fromString("10.1"))); assertThat(strategy.readNumber(fromString("10.1"))).isEqualTo(10.1);
assertEquals(3.141592653589793D, strategy.readNumber(fromString("3.141592653589793238462643383279"))); assertThat(strategy.readNumber(fromString("3.141592653589793238462643383279"))).isEqualTo(3.141592653589793D);
try { try {
strategy.readNumber(fromString("1e400")); strategy.readNumber(fromString("1e400"));
fail(); fail();
} catch (MalformedJsonException expected) { } 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 { try {
strategy.readNumber(fromString("\"not-a-number\"")); strategy.readNumber(fromString("\"not-a-number\""));
@ -49,65 +49,65 @@ public class ToNumberPolicyTest {
@Test @Test
public void testLazilyParsedNumber() throws IOException { public void testLazilyParsedNumber() throws IOException {
ToNumberStrategy strategy = ToNumberPolicy.LAZILY_PARSED_NUMBER; ToNumberStrategy strategy = ToNumberPolicy.LAZILY_PARSED_NUMBER;
assertEquals(new LazilyParsedNumber("10.1"), strategy.readNumber(fromString("10.1"))); assertThat(strategy.readNumber(fromString("10.1"))).isEqualTo(new LazilyParsedNumber("10.1"));
assertEquals(new LazilyParsedNumber("3.141592653589793238462643383279"), strategy.readNumber(fromString("3.141592653589793238462643383279"))); assertThat(strategy.readNumber(fromString("3.141592653589793238462643383279"))).isEqualTo(new LazilyParsedNumber("3.141592653589793238462643383279"));
assertEquals(new LazilyParsedNumber("1e400"), strategy.readNumber(fromString("1e400"))); assertThat(strategy.readNumber(fromString("1e400"))).isEqualTo(new LazilyParsedNumber("1e400"));
} }
@Test @Test
public void testLongOrDouble() throws IOException { public void testLongOrDouble() throws IOException {
ToNumberStrategy strategy = ToNumberPolicy.LONG_OR_DOUBLE; ToNumberStrategy strategy = ToNumberPolicy.LONG_OR_DOUBLE;
assertEquals(10L, strategy.readNumber(fromString("10"))); assertThat(strategy.readNumber(fromString("10"))).isEqualTo(10L);
assertEquals(10.1, strategy.readNumber(fromString("10.1"))); assertThat(strategy.readNumber(fromString("10.1"))).isEqualTo(10.1);
assertEquals(3.141592653589793D, strategy.readNumber(fromString("3.141592653589793238462643383279"))); assertThat(strategy.readNumber(fromString("3.141592653589793238462643383279"))).isEqualTo(3.141592653589793D);
try { try {
strategy.readNumber(fromString("1e400")); strategy.readNumber(fromString("1e400"));
fail(); fail();
} catch (MalformedJsonException expected) { } 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 { try {
strategy.readNumber(fromString("\"not-a-number\"")); strategy.readNumber(fromString("\"not-a-number\""));
fail(); fail();
} catch (JsonParseException expected) { } 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"))); assertThat(strategy.readNumber(fromStringLenient("NaN"))).isEqualTo(Double.NaN);
assertEquals(Double.POSITIVE_INFINITY, strategy.readNumber(fromStringLenient("Infinity"))); assertThat(strategy.readNumber(fromStringLenient("Infinity"))).isEqualTo(Double.POSITIVE_INFINITY);
assertEquals(Double.NEGATIVE_INFINITY, strategy.readNumber(fromStringLenient("-Infinity"))); assertThat(strategy.readNumber(fromStringLenient("-Infinity"))).isEqualTo(Double.NEGATIVE_INFINITY);
try { try {
strategy.readNumber(fromString("NaN")); strategy.readNumber(fromString("NaN"));
fail(); fail();
} catch (MalformedJsonException expected) { } 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 { try {
strategy.readNumber(fromString("Infinity")); strategy.readNumber(fromString("Infinity"));
fail(); fail();
} catch (MalformedJsonException expected) { } 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 { try {
strategy.readNumber(fromString("-Infinity")); strategy.readNumber(fromString("-Infinity"));
fail(); fail();
} catch (MalformedJsonException expected) { } 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 @Test
public void testBigDecimal() throws IOException { public void testBigDecimal() throws IOException {
ToNumberStrategy strategy = ToNumberPolicy.BIG_DECIMAL; ToNumberStrategy strategy = ToNumberPolicy.BIG_DECIMAL;
assertEquals(new BigDecimal("10.1"), strategy.readNumber(fromString("10.1"))); assertThat(strategy.readNumber(fromString("10.1"))).isEqualTo(new BigDecimal("10.1"));
assertEquals(new BigDecimal("3.141592653589793238462643383279"), strategy.readNumber(fromString("3.141592653589793238462643383279"))); assertThat(strategy.readNumber(fromString("3.141592653589793238462643383279"))).isEqualTo(new BigDecimal("3.141592653589793238462643383279"));
assertEquals(new BigDecimal("1e400"), strategy.readNumber(fromString("1e400"))); assertThat(strategy.readNumber(fromString("1e400"))).isEqualTo(new BigDecimal("1e400"));
try { try {
strategy.readNumber(fromString("\"not-a-number\"")); strategy.readNumber(fromString("\"not-a-number\""));
fail(); fail();
} catch (JsonParseException expected) { } 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; package com.google.gson;
import static org.junit.Assert.assertEquals; import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonReader;
@ -23,8 +22,8 @@ public class TypeAdapterTest {
} }
}.nullSafe(); }.nullSafe();
assertEquals("null", adapter.toJson(null)); assertThat(adapter.toJson(null)).isEqualTo("null");
assertNull(adapter.fromJson("null")); assertThat(adapter.fromJson("null")).isNull();
} }
/** /**
@ -39,7 +38,7 @@ public class TypeAdapterTest {
throw exception; throw exception;
} }
@Override public Integer read(JsonReader in) throws IOException { @Override public Integer read(JsonReader in) {
throw new AssertionError("not needed by this test"); throw new AssertionError("not needed by this test");
} }
}; };
@ -48,14 +47,14 @@ public class TypeAdapterTest {
adapter.toJson(1); adapter.toJson(1);
fail(); fail();
} catch (JsonIOException e) { } catch (JsonIOException e) {
assertEquals(exception, e.getCause()); assertThat(e.getCause()).isEqualTo(exception);
} }
try { try {
adapter.toJsonTree(1); adapter.toJsonTree(1);
fail(); fail();
} catch (JsonIOException e) { } 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 // whether that behavior is actually desired
@Test @Test
public void testFromJson_Reader_TrailingData() throws IOException { 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 // Note: This test just verifies the current behavior; it is a bit questionable
// whether that behavior is actually desired // whether that behavior is actually desired
@Test @Test
public void testFromJson_String_TrailingData() throws IOException { 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; package com.google.gson;
import static org.junit.Assert.assertFalse; import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertTrue;
import com.google.gson.annotations.Since; import com.google.gson.annotations.Since;
import com.google.gson.annotations.Until; import com.google.gson.annotations.Until;
@ -35,41 +34,41 @@ public class VersionExclusionStrategyTest {
@Test @Test
public void testSameVersion() throws Exception { public void testSameVersion() throws Exception {
Excluder excluder = Excluder.DEFAULT.withVersion(VERSION); Excluder excluder = Excluder.DEFAULT.withVersion(VERSION);
assertFalse(excluder.excludeClass(MockClassSince.class, true)); assertThat(excluder.excludeClass(MockClassSince.class, true)).isFalse();
assertFalse(excluder.excludeField(MockClassSince.class.getField("someField"), true)); assertThat(excluder.excludeField(MockClassSince.class.getField("someField"), true)).isFalse();
// Until version is exclusive // Until version is exclusive
assertTrue(excluder.excludeClass(MockClassUntil.class, true)); assertThat(excluder.excludeClass(MockClassUntil.class, true)).isTrue();
assertTrue(excluder.excludeField(MockClassUntil.class.getField("someField"), true)); assertThat(excluder.excludeField(MockClassUntil.class.getField("someField"), true)).isTrue();
assertFalse(excluder.excludeClass(MockClassBoth.class, true)); assertThat(excluder.excludeClass(MockClassBoth.class, true)).isFalse();
assertFalse(excluder.excludeField(MockClassBoth.class.getField("someField"), true)); assertThat(excluder.excludeField(MockClassBoth.class.getField("someField"), true)).isFalse();
} }
@Test @Test
public void testNewerVersion() throws Exception { public void testNewerVersion() throws Exception {
Excluder excluder = Excluder.DEFAULT.withVersion(VERSION + 5); Excluder excluder = Excluder.DEFAULT.withVersion(VERSION + 5);
assertFalse(excluder.excludeClass(MockClassSince.class, true)); assertThat(excluder.excludeClass(MockClassSince.class, true)).isFalse();
assertFalse(excluder.excludeField(MockClassSince.class.getField("someField"), true)); assertThat(excluder.excludeField(MockClassSince.class.getField("someField"), true)).isFalse();
assertTrue(excluder.excludeClass(MockClassUntil.class, true)); assertThat(excluder.excludeClass(MockClassUntil.class, true)).isTrue();
assertTrue(excluder.excludeField(MockClassUntil.class.getField("someField"), true)); assertThat(excluder.excludeField(MockClassUntil.class.getField("someField"), true)).isTrue();
assertTrue(excluder.excludeClass(MockClassBoth.class, true)); assertThat(excluder.excludeClass(MockClassBoth.class, true)).isTrue();
assertTrue(excluder.excludeField(MockClassBoth.class.getField("someField"), true)); assertThat(excluder.excludeField(MockClassBoth.class.getField("someField"), true)).isTrue();
} }
@Test @Test
public void testOlderVersion() throws Exception { public void testOlderVersion() throws Exception {
Excluder excluder = Excluder.DEFAULT.withVersion(VERSION - 5); Excluder excluder = Excluder.DEFAULT.withVersion(VERSION - 5);
assertTrue(excluder.excludeClass(MockClassSince.class, true)); assertThat(excluder.excludeClass(MockClassSince.class, true)).isTrue();
assertTrue(excluder.excludeField(MockClassSince.class.getField("someField"), true)); assertThat(excluder.excludeField(MockClassSince.class.getField("someField"), true)).isTrue();
assertFalse(excluder.excludeClass(MockClassUntil.class, true)); assertThat(excluder.excludeClass(MockClassUntil.class, true)).isFalse();
assertFalse(excluder.excludeField(MockClassUntil.class.getField("someField"), true)); assertThat(excluder.excludeField(MockClassUntil.class.getField("someField"), true)).isFalse();
assertTrue(excluder.excludeClass(MockClassBoth.class, true)); assertThat(excluder.excludeClass(MockClassBoth.class, true)).isTrue();
assertTrue(excluder.excludeField(MockClassBoth.class.getField("someField"), true)); assertThat(excluder.excludeField(MockClassBoth.class.getField("someField"), true)).isTrue();
} }
@Since(VERSION) @Since(VERSION)