Merge remote-tracking branch 'origin/master'
ci/woodpecker/push/woodpecker Pipeline was successful Details

# Conflicts:
#	extras/pom.xml
#	extras/src/main/java/com/google/gson/graph/GraphAdapterBuilder.java
#	extras/src/main/java/com/google/gson/interceptors/InterceptorFactory.java
#	extras/src/test/java/com/google/gson/typeadapters/PostConstructAdapterFactoryTest.java
#	gson/src/main/java/com/google/gson/Gson.java
#	gson/src/main/java/com/google/gson/GsonBuilder.java
#	gson/src/main/java/com/google/gson/util/ISO8601Utils.java
#	gson/src/main/java/module-info.java
#	gson/src/test/java/com/google/gson/GsonTest.java
#	gson/src/test/java/com/google/gson/functional/ArrayTest.java
#	gson/src/test/java/com/google/gson/functional/CustomTypeAdaptersTest.java
#	gson/src/test/java/com/google/gson/functional/DefaultTypeAdaptersTest.java
#	gson/src/test/java/com/google/gson/functional/EnumWithObfuscatedTest.java
#	gson/src/test/java/com/google/gson/functional/InternationalizationTest.java
#	gson/src/test/java/com/google/gson/functional/Java17RecordTest.java
#	gson/src/test/java/com/google/gson/functional/JavaUtilConcurrentAtomicTest.java
#	gson/src/test/java/com/google/gson/functional/JavaUtilTest.java
#	gson/src/test/java/com/google/gson/functional/JsonAdapterAnnotationOnClassesTest.java
#	gson/src/test/java/com/google/gson/functional/JsonAdapterAnnotationOnFieldsTest.java
#	gson/src/test/java/com/google/gson/functional/JsonParserTest.java
#	gson/src/test/java/com/google/gson/functional/MapTest.java
#	gson/src/test/java/com/google/gson/functional/PrimitiveTest.java
#	gson/src/test/java/com/google/gson/functional/ReflectionAccessTest.java
#	gson/src/test/java/com/google/gson/functional/StreamingTypeAdaptersTest.java
#	gson/src/test/java/com/google/gson/functional/TypeAdapterPrecedenceTest.java
#	gson/src/test/java/com/google/gson/internal/bind/Java17ReflectiveTypeAdapterFactoryTest.java
#	gson/src/test/java/com/google/gson/internal/bind/JsonTreeReaderTest.java
#	gson/src/test/java/com/google/gson/internal/bind/JsonTreeWriterTest.java
#	gson/src/test/java/com/google/gson/internal/reflect/Java17ReflectionHelperTest.java
#	gson/src/test/java/com/google/gson/regression/JsonAdapterNullSafeTest.java
#	gson/src/test/java/com/google/gson/stream/JsonReaderPathTest.java
#	gson/src/test/java/com/google/gson/stream/JsonReaderTest.java
#	metrics/pom.xml
#	metrics/src/main/java/com/google/gson/metrics/NonUploadingCaliperRunner.java
#	metrics/src/main/java/com/google/gson/metrics/ParseBenchmark.java
#	pom.xml
#	proto/pom.xml
This commit is contained in:
Johannes Frohnmeyer 2023-02-23 14:02:45 +01:00
commit 89ae8b48c2
Signed by: Johannes
GPG Key ID: E76429612C2929F4
128 changed files with 3235 additions and 2501 deletions

View File

@ -1,3 +1,19 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
Copyright 2008 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
@ -29,6 +45,12 @@
<version>1.1.3</version> <version>1.1.3</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava-testlib</artifactId>
<version>31.1-jre</version>
<scope>test</scope>
</dependency>
</dependencies> </dependencies>
<build> <build>
@ -103,7 +125,7 @@
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId> <artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M8</version> <version>3.0.0-M9</version>
<configuration> <configuration>
<!-- Deny illegal access, this is required for ReflectionAccessTest --> <!-- Deny illegal access, this is required for ReflectionAccessTest -->
<!-- Requires Java >= 9; Important: In case future Java versions <!-- Requires Java >= 9; Important: In case future Java versions

View File

@ -93,12 +93,16 @@ package com.google.gson;
public interface ExclusionStrategy { public interface ExclusionStrategy {
/** /**
* Decides if a field should be skipped during serialization or deserialization.
*
* @param f the field object that is under test * @param f the field object that is under test
* @return true if the field should be ignored; otherwise false * @return true if the field should be ignored; otherwise false
*/ */
public boolean shouldSkipField(FieldAttributes f); public boolean shouldSkipField(FieldAttributes f);
/** /**
* Decides if a class should be serialized or deserialized
*
* @param clazz the class object that is under test * @param clazz the class object that is under test
* @return true if the class should be ignored; otherwise false * @return true if the class should be ignored; otherwise false
*/ */

View File

@ -46,6 +46,8 @@ public final class FieldAttributes {
} }
/** /**
* Gets the declaring Class that contains this field
*
* @return the declaring class that contains this field * @return the declaring class that contains this field
*/ */
public Class<?> getDeclaringClass() { public Class<?> getDeclaringClass() {
@ -53,6 +55,8 @@ public final class FieldAttributes {
} }
/** /**
* Gets the name of the field
*
* @return the name of the field * @return the name of the field
*/ */
public String getName() { public String getName() {

View File

@ -0,0 +1,98 @@
/*
* Copyright (C) 2022 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.gson;
import java.util.Objects;
/**
* A class used to control what the serialization looks like.
*
* <p>It currently defines the kind of newline to use, and the indent, but
* might add more in the future.</p>
*
* @see <a href="https://en.wikipedia.org/wiki/Newline">Wikipedia Newline article</a>
*
* @since $next-version$
*/
public class FormattingStyle {
private final String newline;
private final String indent;
static public final FormattingStyle DEFAULT =
new FormattingStyle("\n", " ");
private FormattingStyle(String newline, String indent) {
Objects.requireNonNull(newline, "newline == null");
Objects.requireNonNull(indent, "indent == null");
if (!newline.matches("[\r\n]*")) {
throw new IllegalArgumentException(
"Only combinations of \\n and \\r are allowed in newline.");
}
if (!indent.matches("[ \t]*")) {
throw new IllegalArgumentException(
"Only combinations of spaces and tabs allowed in indent.");
}
this.newline = newline;
this.indent = indent;
}
/**
* Creates a {@link FormattingStyle} with the specified newline setting.
*
* <p>It can be used to accommodate certain OS convention, for example
* hardcode {@code "\r"} for Linux and macos, {@code "\r\n"} for Windows, or
* call {@link java.lang.System#lineSeparator()} to match the current OS.</p>
*
* <p>Only combinations of {@code \n} and {@code \r} are allowed.</p>
*
* @param newline the string value that will be used as newline.
* @return a newly created {@link FormattingStyle}
*/
public FormattingStyle withNewline(String newline) {
return new FormattingStyle(newline, this.indent);
}
/**
* Creates a {@link FormattingStyle} with the specified indent string.
*
* <p>Only combinations of spaces and tabs allowed in indent.</p>
*
* @param indent the string value that will be used as indent.
* @return a newly created {@link FormattingStyle}
*/
public FormattingStyle withIndent(String indent) {
return new FormattingStyle(this.newline, indent);
}
/**
* The string value that will be used as a newline.
*
* @return the newline value.
*/
public String getNewline() {
return this.newline;
}
/**
* The string value that will be used as indent.
*
* @return the indent value.
*/
public String getIndent() {
return this.indent;
}
}

View File

@ -64,8 +64,8 @@ import java.util.concurrent.atomic.AtomicLongArray;
* *
* <p>You can create a Gson instance by invoking {@code new Gson()} if the default configuration * <p>You can create a Gson instance by invoking {@code new Gson()} if the default configuration
* is all you need. You can also use {@link GsonBuilder} to build a Gson instance with various * is all you need. You can also use {@link GsonBuilder} to build a Gson instance with various
* configuration options such as versioning support, pretty printing, custom * configuration options such as versioning support, pretty printing, custom newline, custom indent,
* {@link JsonSerializer}s, {@link JsonDeserializer}s, and {@link InstanceCreator}s.</p> * custom {@link JsonSerializer}s, {@link JsonDeserializer}s, and {@link InstanceCreator}s.</p>
* *
* <p>Here is an example of how Gson is used for a simple Class: * <p>Here is an example of how Gson is used for a simple Class:
* *
@ -146,6 +146,7 @@ public final class Gson {
* with the type token provided to {@code getAdapter} as key and either * with the type token provided to {@code getAdapter} as key and either
* {@code FutureTypeAdapter} or a regular {@code TypeAdapter} as value. * {@code FutureTypeAdapter} or a regular {@code TypeAdapter} as value.
*/ */
@SuppressWarnings("ThreadLocalUsage")
private final ThreadLocal<Map<TypeToken<?>, TypeAdapter<?>>> threadLocalAdapterResults = new ThreadLocal<>(); private final ThreadLocal<Map<TypeToken<?>, TypeAdapter<?>>> threadLocalAdapterResults = new ThreadLocal<>();
private final ConcurrentMap<TypeToken<?>, TypeAdapter<?>> typeTokenCache = new ConcurrentHashMap<>(); private final ConcurrentMap<TypeToken<?>, TypeAdapter<?>> typeTokenCache = new ConcurrentHashMap<>();
@ -163,7 +164,7 @@ public final class Gson {
final boolean duplicateMapKeyDeserialization; final boolean duplicateMapKeyDeserialization;
final boolean generateNonExecutableJson; final boolean generateNonExecutableJson;
final boolean htmlSafe; final boolean htmlSafe;
final boolean prettyPrinting; final FormattingStyle formattingStyle;
final boolean lenient; final boolean lenient;
final boolean omitQuotes; final boolean omitQuotes;
final boolean serializeSpecialFloatingPointValues; final boolean serializeSpecialFloatingPointValues;
@ -184,7 +185,9 @@ public final class Gson {
* <ul> * <ul>
* <li>The JSON generated by <code>toJson</code> methods is in compact representation. This * <li>The JSON generated by <code>toJson</code> methods is in compact representation. This
* means that all the unneeded white-space is removed. You can change this behavior with * means that all the unneeded white-space is removed. You can change this behavior with
* {@link GsonBuilder#setPrettyPrinting()}. </li> * {@link GsonBuilder#setPrettyPrinting()}.</li>
* <li>When the JSON generated contains more than one line, the kind of newline and indent to
* use can be configured with {@link GsonBuilder#setPrettyPrinting(FormattingStyle)}.</li>
* <li>The generated JSON omits all the fields that are null. Note that nulls in arrays are * <li>The generated JSON omits all the fields that are null. Note that nulls in arrays are
* kept as is since an array is an ordered list. Moreover, if a field is not null, but its * kept as is since an array is an ordered list. Moreover, if a field is not null, but its
* generated JSON is empty, the field is kept. You can configure Gson to serialize null values * generated JSON is empty, the field is kept. You can configure Gson to serialize null values
@ -216,7 +219,7 @@ public final class Gson {
this(Excluder.DEFAULT, DefaultConfig.DEFAULT_FIELD_NAMING_STRATEGY, this(Excluder.DEFAULT, DefaultConfig.DEFAULT_FIELD_NAMING_STRATEGY,
Collections.<Type, InstanceCreator<?>>emptyMap(), DefaultConfig.DEFAULT_SERIALIZE_NULLS, Collections.<Type, InstanceCreator<?>>emptyMap(), DefaultConfig.DEFAULT_SERIALIZE_NULLS,
DefaultConfig.DEFAULT_COMPLEX_MAP_KEYS, DefaultConfig.DEFAULT_DUPLICATE_MAP_KEYS, DefaultConfig.DEFAULT_JSON_NON_EXECUTABLE, DefaultConfig.DEFAULT_ESCAPE_HTML, DefaultConfig.DEFAULT_COMPLEX_MAP_KEYS, DefaultConfig.DEFAULT_DUPLICATE_MAP_KEYS, DefaultConfig.DEFAULT_JSON_NON_EXECUTABLE, DefaultConfig.DEFAULT_ESCAPE_HTML,
DefaultConfig.DEFAULT_PRETTY_PRINT, true, DefaultConfig.DEFAULT_OMIT_QUOTES, DefaultConfig.DEFAULT_SPECIALIZE_FLOAT_VALUES, DefaultConfig.DEFAULT_FORMATTING_STYLE, true, DefaultConfig.DEFAULT_OMIT_QUOTES, DefaultConfig.DEFAULT_SPECIALIZE_FLOAT_VALUES,
DefaultConfig.DEFAULT_USE_JDK_UNSAFE, DefaultConfig.DEFAULT_USE_JDK_UNSAFE,
LongSerializationPolicy.DEFAULT, DefaultConfig.DEFAULT_DATE_PATTERN, DateFormat.DEFAULT, DateFormat.DEFAULT, LongSerializationPolicy.DEFAULT, DefaultConfig.DEFAULT_DATE_PATTERN, DateFormat.DEFAULT, DateFormat.DEFAULT,
Collections.<TypeAdapterFactory>emptyList(), Collections.<TypeAdapterFactory>emptyList(), Collections.<TypeAdapterFactory>emptyList(), Collections.<TypeAdapterFactory>emptyList(),
@ -227,7 +230,7 @@ public final class Gson {
Gson(Excluder excluder, FieldNamingStrategy fieldNamingStrategy, Gson(Excluder excluder, FieldNamingStrategy fieldNamingStrategy,
Map<Type, InstanceCreator<?>> instanceCreators, boolean serializeNulls, Map<Type, InstanceCreator<?>> instanceCreators, boolean serializeNulls,
boolean complexMapKeySerialization, boolean duplicateMapKeyDeserialization, boolean generateNonExecutableGson, boolean htmlSafe, boolean complexMapKeySerialization, boolean duplicateMapKeyDeserialization, boolean generateNonExecutableGson, boolean htmlSafe,
boolean prettyPrinting, boolean lenient, boolean omitQuotes, boolean serializeSpecialFloatingPointValues, FormattingStyle formattingStyle, boolean lenient, boolean omitQuotes, boolean serializeSpecialFloatingPointValues,
boolean useJdkUnsafe, boolean useJdkUnsafe,
LongSerializationPolicy longSerializationPolicy, String datePattern, int dateStyle, LongSerializationPolicy longSerializationPolicy, String datePattern, int dateStyle,
int timeStyle, List<TypeAdapterFactory> builderFactories, int timeStyle, List<TypeAdapterFactory> builderFactories,
@ -244,7 +247,7 @@ public final class Gson {
this.duplicateMapKeyDeserialization = duplicateMapKeyDeserialization; this.duplicateMapKeyDeserialization = duplicateMapKeyDeserialization;
this.generateNonExecutableJson = generateNonExecutableGson; this.generateNonExecutableJson = generateNonExecutableGson;
this.htmlSafe = htmlSafe; this.htmlSafe = htmlSafe;
this.prettyPrinting = prettyPrinting; this.formattingStyle = formattingStyle;
this.lenient = lenient; this.lenient = lenient;
this.omitQuotes = omitQuotes; this.omitQuotes = omitQuotes;
this.serializeSpecialFloatingPointValues = serializeSpecialFloatingPointValues; this.serializeSpecialFloatingPointValues = serializeSpecialFloatingPointValues;
@ -677,7 +680,7 @@ public final class Gson {
* <pre> * <pre>
* Type typeOfSrc = new TypeToken&lt;Collection&lt;Foo&gt;&gt;(){}.getType(); * Type typeOfSrc = new TypeToken&lt;Collection&lt;Foo&gt;&gt;(){}.getType();
* </pre> * </pre>
* @return Json representation of {@code src} * @return JSON representation of {@code src}.
* @since 1.4 * @since 1.4
* *
* @see #toJsonTree(Object) * @see #toJsonTree(Object)
@ -699,7 +702,7 @@ public final class Gson {
* {@link Writer}, use {@link #toJson(Object, Appendable)} instead. * {@link Writer}, use {@link #toJson(Object, Appendable)} instead.
* *
* @param src the object for which JSON representation is to be created * @param src the object for which JSON representation is to be created
* @return Json representation of {@code src}. * @return JSON representation of {@code src}.
* *
* @see #toJson(Object, Appendable) * @see #toJson(Object, Appendable)
* @see #toJson(Object, Type) * @see #toJson(Object, Type)
@ -724,7 +727,7 @@ public final class Gson {
* <pre> * <pre>
* Type typeOfSrc = new TypeToken&lt;Collection&lt;Foo&gt;&gt;(){}.getType(); * Type typeOfSrc = new TypeToken&lt;Collection&lt;Foo&gt;&gt;(){}.getType();
* </pre> * </pre>
* @return JSON representation of {@code src} * @return JSON representation of {@code src}.
* *
* @see #toJson(Object, Type, Appendable) * @see #toJson(Object, Type, Appendable)
* @see #toJson(Object) * @see #toJson(Object)
@ -833,7 +836,7 @@ public final class Gson {
* Converts a tree of {@link JsonElement}s into its equivalent JSON representation. * Converts a tree of {@link JsonElement}s into its equivalent JSON representation.
* *
* @param jsonElement root of a tree of {@link JsonElement}s * @param jsonElement root of a tree of {@link JsonElement}s
* @return JSON String representation of the tree * @return JSON String representation of the tree.
* @since 1.4 * @since 1.4
*/ */
public String toJson(JsonElement jsonElement) { public String toJson(JsonElement jsonElement) {
@ -870,6 +873,7 @@ public final class Gson {
* <li>{@link GsonBuilder#setLenient()}</li> * <li>{@link GsonBuilder#setLenient()}</li>
* <li>{@link GsonBuilder#setOmitQuotes()}</li> * <li>{@link GsonBuilder#setOmitQuotes()}</li>
* <li>{@link GsonBuilder#setPrettyPrinting()}</li> * <li>{@link GsonBuilder#setPrettyPrinting()}</li>
* <li>{@link GsonBuilder#setPrettyPrinting(FormattingStyle)}</li>
* </ul> * </ul>
*/ */
public JsonWriter newJsonWriter(Writer writer) throws IOException { public JsonWriter newJsonWriter(Writer writer) throws IOException {
@ -877,9 +881,7 @@ public final class Gson {
writer.write(DefaultConfig.JSON_NON_EXECUTABLE_PREFIX); writer.write(DefaultConfig.JSON_NON_EXECUTABLE_PREFIX);
} }
JsonWriter jsonWriter = new JsonWriter(writer); JsonWriter jsonWriter = new JsonWriter(writer);
if (prettyPrinting) { jsonWriter.setFormattingStyle(formattingStyle);
jsonWriter.setIndent(" ");
}
jsonWriter.setHtmlSafe(htmlSafe); jsonWriter.setHtmlSafe(htmlSafe);
jsonWriter.setLenient(lenient); jsonWriter.setLenient(lenient);
jsonWriter.setOmitQuotes(omitQuotes); jsonWriter.setOmitQuotes(omitQuotes);

View File

@ -31,11 +31,11 @@ import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter; import com.google.gson.stream.JsonWriter;
import java.lang.reflect.Type; import java.lang.reflect.Type;
import java.text.DateFormat; import java.text.DateFormat;
import java.util.ArrayDeque;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.Date; import java.util.Date;
import java.util.HashMap; import java.util.HashMap;
import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Objects; import java.util.Objects;
@ -89,14 +89,14 @@ public final class GsonBuilder {
private boolean duplicateMapKeyDeserialization = DEFAULT_DUPLICATE_MAP_KEYS; private boolean duplicateMapKeyDeserialization = DEFAULT_DUPLICATE_MAP_KEYS;
private boolean serializeSpecialFloatingPointValues = DEFAULT_SPECIALIZE_FLOAT_VALUES; private boolean serializeSpecialFloatingPointValues = DEFAULT_SPECIALIZE_FLOAT_VALUES;
private boolean escapeHtmlChars = DEFAULT_ESCAPE_HTML; private boolean escapeHtmlChars = DEFAULT_ESCAPE_HTML;
private boolean prettyPrinting = DEFAULT_PRETTY_PRINT; private FormattingStyle formattingStyle = DEFAULT_FORMATTING_STYLE;
private boolean generateNonExecutableJson = DEFAULT_JSON_NON_EXECUTABLE; private boolean generateNonExecutableJson = DEFAULT_JSON_NON_EXECUTABLE;
private boolean lenient = DEFAULT_LENIENT; private boolean lenient = DEFAULT_LENIENT;
private boolean omitQuotes = DEFAULT_OMIT_QUOTES; private boolean omitQuotes = DEFAULT_OMIT_QUOTES;
private boolean useJdkUnsafe = DEFAULT_USE_JDK_UNSAFE; private boolean useJdkUnsafe = DEFAULT_USE_JDK_UNSAFE;
private ToNumberStrategy objectToNumberStrategy = DEFAULT_OBJECT_TO_NUMBER_STRATEGY; private ToNumberStrategy objectToNumberStrategy = DEFAULT_OBJECT_TO_NUMBER_STRATEGY;
private ToNumberStrategy numberToNumberStrategy = DEFAULT_NUMBER_TO_NUMBER_STRATEGY; private ToNumberStrategy numberToNumberStrategy = DEFAULT_NUMBER_TO_NUMBER_STRATEGY;
private final LinkedList<ReflectionAccessFilter> reflectionFilters = new LinkedList<>(); private final ArrayDeque<ReflectionAccessFilter> reflectionFilters = new ArrayDeque<>();
/** /**
* Creates a GsonBuilder instance that can be used to build Gson with various configuration * Creates a GsonBuilder instance that can be used to build Gson with various configuration
@ -122,7 +122,7 @@ public final class GsonBuilder {
this.duplicateMapKeyDeserialization = gson.duplicateMapKeyDeserialization; this.duplicateMapKeyDeserialization = gson.duplicateMapKeyDeserialization;
this.generateNonExecutableJson = gson.generateNonExecutableJson; this.generateNonExecutableJson = gson.generateNonExecutableJson;
this.escapeHtmlChars = gson.htmlSafe; this.escapeHtmlChars = gson.htmlSafe;
this.prettyPrinting = gson.prettyPrinting; this.formattingStyle = gson.formattingStyle;
this.lenient = gson.lenient; this.lenient = gson.lenient;
this.omitQuotes = gson.omitQuotes; this.omitQuotes = gson.omitQuotes;
this.serializeSpecialFloatingPointValues = gson.serializeSpecialFloatingPointValues; this.serializeSpecialFloatingPointValues = gson.serializeSpecialFloatingPointValues;
@ -488,13 +488,26 @@ public final class GsonBuilder {
} }
/** /**
* Configures Gson to output Json that fits in a page for pretty printing. This option only * Configures Gson to output JSON that fits in a page for pretty printing. This option only
* affects Json serialization. * affects JSON serialization.
* *
* @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern * @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern
*/ */
public GsonBuilder setPrettyPrinting() { public GsonBuilder setPrettyPrinting() {
prettyPrinting = true; return setPrettyPrinting(FormattingStyle.DEFAULT);
}
/**
* Configures Gson to output JSON that uses a certain kind of formatting stile (for example newline and indent).
* This option only affects JSON serialization.
*
* <p>Has no effect if the serialized format is a single line.</p>
*
* @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern
* @since $next-version$
*/
public GsonBuilder setPrettyPrinting(FormattingStyle formattingStyle) {
this.formattingStyle = formattingStyle;
return this; return this;
} }
@ -780,7 +793,7 @@ public final class GsonBuilder {
return new Gson(excluder, fieldNamingPolicy, new HashMap<>(instanceCreators), return new Gson(excluder, fieldNamingPolicy, new HashMap<>(instanceCreators),
serializeNulls, complexMapKeySerialization, duplicateMapKeyDeserialization, serializeNulls, complexMapKeySerialization, duplicateMapKeyDeserialization,
generateNonExecutableJson, escapeHtmlChars, prettyPrinting, lenient, omitQuotes, generateNonExecutableJson, escapeHtmlChars, formattingStyle, lenient, omitQuotes,
serializeSpecialFloatingPointValues, useJdkUnsafe, longSerializationPolicy, serializeSpecialFloatingPointValues, useJdkUnsafe, longSerializationPolicy,
datePattern, dateStyle, timeStyle, new ArrayList<>(this.factories), datePattern, dateStyle, timeStyle, new ArrayList<>(this.factories),
new ArrayList<>(this.hierarchyFactories), factories, new ArrayList<>(this.hierarchyFactories), factories,

View File

@ -89,7 +89,7 @@ public interface JsonDeserializer<T> {
* @param json The Json data being deserialized * @param json The Json data being deserialized
* @param typeOfT The type of the Object to deserialize to * @param typeOfT The type of the Object to deserialize to
* @return a deserialized object of the specified type typeOfT which is a subclass of {@code T} * @return a deserialized object of the specified type typeOfT which is a subclass of {@code T}
* @throws JsonParseException if json is not in the expected format of {@code typeofT} * @throws JsonParseException if json is not in the expected format of {@code typeOfT}
*/ */
public T deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) public T deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException; throws JsonParseException;

View File

@ -106,7 +106,7 @@ public final class JsonPrimitive extends JsonElement {
if (isBoolean()) { if (isBoolean()) {
return (Boolean) value; return (Boolean) value;
} }
// Check to see if the value as a String is "true" in any case. // Check to see if the value as a String is "true" in any case.
return Boolean.parseBoolean(getAsString()); return Boolean.parseBoolean(getAsString());
} }
@ -180,8 +180,11 @@ public final class JsonPrimitive extends JsonElement {
*/ */
@Override @Override
public BigInteger getAsBigInteger() { public BigInteger getAsBigInteger() {
return value instanceof BigInteger ? return value instanceof BigInteger
(BigInteger) value : new BigInteger(getAsString()); ? (BigInteger) value
: isIntegral(this)
? BigInteger.valueOf(this.getAsNumber().longValue())
: new BigInteger(this.getAsString());
} }
/** /**
@ -282,7 +285,9 @@ public final class JsonPrimitive extends JsonElement {
return other.value == null; return other.value == null;
} }
if (isIntegral(this) && isIntegral(other)) { if (isIntegral(this) && isIntegral(other)) {
return getAsNumber().longValue() == other.getAsNumber().longValue(); return this.value instanceof BigInteger || other.value instanceof BigInteger
? this.getAsBigInteger().equals(other.getAsBigInteger())
: this.getAsNumber().longValue() == other.getAsNumber().longValue();
} }
if (value instanceof Number && other.value instanceof Number) { if (value instanceof Number && other.value instanceof Number) {
double a = getAsNumber().doubleValue(); double a = getAsNumber().doubleValue();

View File

@ -1,3 +1,19 @@
/*
* Copyright (C) 2022 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.gson; package com.google.gson;
import com.google.gson.internal.ReflectionAccessFilterHelper; import com.google.gson.internal.ReflectionAccessFilterHelper;

View File

@ -83,10 +83,14 @@ import java.lang.annotation.Target;
public @interface SerializedName { public @interface SerializedName {
/** /**
* The desired name of the field when it is serialized or deserialized.
*
* @return the desired name of the field when it is serialized or deserialized * @return the desired name of the field when it is serialized or deserialized
*/ */
String value(); String value();
/** /**
* The alternative names of the field when it is deserialized
*
* @return the alternative names of the field when it is deserialized * @return the alternative names of the field when it is deserialized
*/ */
String[] alternate() default {}; String[] alternate() default {};

View File

@ -1,6 +1,22 @@
/*
* Copyright (C) 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/** /**
* This package provides annotations that can be used with {@link com.google.gson.Gson}. * This package provides annotations that can be used with {@link com.google.gson.Gson}.
* *
* @author Inderjeet Singh, Joel Leitch * @author Inderjeet Singh, Joel Leitch
*/ */
package com.google.gson.annotations; package com.google.gson.annotations;

View File

@ -342,8 +342,8 @@ public final class ConstructorConstructor {
return (T) new TreeMap<>(); return (T) new TreeMap<>();
} }
}; };
} else if (type instanceof ParameterizedType && !(String.class.isAssignableFrom( } else if (type instanceof ParameterizedType && !String.class.isAssignableFrom(
TypeToken.get(((ParameterizedType) type).getActualTypeArguments()[0]).getRawType()))) { TypeToken.get(((ParameterizedType) type).getActualTypeArguments()[0]).getRawType())) {
return new ObjectConstructor<T>() { return new ObjectConstructor<T>() {
@Override public T construct() { @Override public T construct() {
return (T) new LinkedHashMap<>(); return (T) new LinkedHashMap<>();

View File

@ -7,7 +7,7 @@ public class DefaultConfig {
public static final boolean DEFAULT_JSON_NON_EXECUTABLE = false; public static final boolean DEFAULT_JSON_NON_EXECUTABLE = false;
public static final boolean DEFAULT_LENIENT = false; public static final boolean DEFAULT_LENIENT = false;
public static final boolean DEFAULT_OMIT_QUOTES = false; public static final boolean DEFAULT_OMIT_QUOTES = false;
public static final boolean DEFAULT_PRETTY_PRINT = false; public static final FormattingStyle DEFAULT_FORMATTING_STYLE = null;
public static final boolean DEFAULT_ESCAPE_HTML = true; public static final boolean DEFAULT_ESCAPE_HTML = true;
public static final boolean DEFAULT_SERIALIZE_NULLS = false; public static final boolean DEFAULT_SERIALIZE_NULLS = false;
public static final boolean DEFAULT_COMPLEX_MAP_KEYS = false; public static final boolean DEFAULT_COMPLEX_MAP_KEYS = false;

View File

@ -75,6 +75,8 @@ public final class JavaVersion {
} }
/** /**
* Gets the major Java version
*
* @return the major Java version, i.e. '8' for Java 1.8, '9' for Java 9 etc. * @return the major Java version, i.e. '8' for Java 1.8, '9' for Java 9 etc.
*/ */
public static int getMajorJavaVersion() { public static int getMajorJavaVersion() {
@ -82,6 +84,8 @@ public final class JavaVersion {
} }
/** /**
* Gets a boolean value depending if the application is running on Java 9 or later
*
* @return {@code true} if the application is running on Java 9 or later; and {@code false} otherwise. * @return {@code true} if the application is running on Java 9 or later; and {@code false} otherwise.
*/ */
public static boolean isJava9OrLater() { public static boolean isJava9OrLater() {

View File

@ -98,7 +98,7 @@ public final class LazilyParsedNumber extends Number {
} }
if (obj instanceof LazilyParsedNumber) { if (obj instanceof LazilyParsedNumber) {
LazilyParsedNumber other = (LazilyParsedNumber) obj; LazilyParsedNumber other = (LazilyParsedNumber) obj;
return value == other.value || value.equals(other.value); return value.equals(other.value);
} }
return false; return false;
} }

View File

@ -304,6 +304,7 @@ public final class LinkedTreeMap<K, V> extends AbstractMap<K, V> implements Seri
return node; return node;
} }
@SuppressWarnings("ReferenceEquality")
private void replaceInParent(Node<K, V> node, Node<K, V> replacement) { private void replaceInParent(Node<K, V> node, Node<K, V> replacement) {
Node<K, V> parent = node.parent; Node<K, V> parent = node.parent;
node.parent = null; node.parent = null;
@ -315,7 +316,7 @@ public final class LinkedTreeMap<K, V> extends AbstractMap<K, V> implements Seri
if (parent.left == node) { if (parent.left == node) {
parent.left = replacement; parent.left = replacement;
} else { } else {
assert (parent.right == node); assert parent.right == node;
parent.right = replacement; parent.right = replacement;
} }
} else { } else {
@ -559,10 +560,13 @@ public final class LinkedTreeMap<K, V> extends AbstractMap<K, V> implements Seri
LinkedTreeMapIterator() { LinkedTreeMapIterator() {
} }
@Override public final boolean hasNext() { @Override
@SuppressWarnings("ReferenceEquality")
public final boolean hasNext() {
return next != header; return next != header;
} }
@SuppressWarnings("ReferenceEquality")
final Node<K, V> nextNode() { final Node<K, V> nextNode() {
Node<K, V> e = next; Node<K, V> e = next;
if (e == header) { if (e == header) {

View File

@ -1,3 +1,19 @@
/*
* Copyright (C) 2018 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.gson.internal; package com.google.gson.internal;
import java.util.AbstractList; import java.util.AbstractList;

View File

@ -1,3 +1,19 @@
/*
* Copyright (C) 2022 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.gson.internal; package com.google.gson.internal;
import java.lang.reflect.AccessibleObject; import java.lang.reflect.AccessibleObject;
@ -82,6 +98,7 @@ public class ReflectionAccessFilterHelper {
} }
}; };
} catch (NoSuchMethodException ignored) { } catch (NoSuchMethodException ignored) {
// OK: will assume everything is accessible
} }
} }

View File

@ -64,6 +64,7 @@ public abstract class UnsafeAllocator {
} }
}; };
} catch (Exception ignored) { } catch (Exception ignored) {
// OK: try the next way
} }
// try dalvikvm, post-gingerbread // try dalvikvm, post-gingerbread
@ -88,6 +89,7 @@ public abstract class UnsafeAllocator {
} }
}; };
} catch (Exception ignored) { } catch (Exception ignored) {
// OK: try the next way
} }
// try dalvikvm, pre-gingerbread // try dalvikvm, pre-gingerbread
@ -108,6 +110,7 @@ public abstract class UnsafeAllocator {
} }
}; };
} catch (Exception ignored) { } catch (Exception ignored) {
// OK: try the next way
} }
// give up // give up

View File

@ -37,7 +37,7 @@ public final class ArrayTypeAdapter<E> extends TypeAdapter<Object> {
public static final TypeAdapterFactory FACTORY = new TypeAdapterFactory() { public static final TypeAdapterFactory FACTORY = new TypeAdapterFactory() {
@Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) { @Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
Type type = typeToken.getType(); Type type = typeToken.getType();
if (!(type instanceof GenericArrayType || type instanceof Class && ((Class<?>) type).isArray())) { if (!(type instanceof GenericArrayType || (type instanceof Class && ((Class<?>) type).isArray()))) {
return null; return null;
} }

View File

@ -81,7 +81,9 @@ public final class DateTypeAdapter extends TypeAdapter<Date> {
for (DateFormat dateFormat : dateFormats) { for (DateFormat dateFormat : dateFormats) {
try { try {
return dateFormat.parse(s); return dateFormat.parse(s);
} catch (ParseException ignored) {} } catch (ParseException ignored) {
// OK: try the next format
}
} }
} }
try { try {

View File

@ -154,7 +154,9 @@ public final class DefaultDateTypeAdapter<T extends Date> extends TypeAdapter<T>
for (DateFormat dateFormat : dateFormats) { for (DateFormat dateFormat : dateFormats) {
try { try {
return dateFormat.parse(s); return dateFormat.parse(s);
} catch (ParseException ignored) {} } catch (ParseException ignored) {
// OK: try the next format
}
} }
} }

View File

@ -1,3 +1,19 @@
/*
* Copyright (C) 2022 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.gson.internal.bind; package com.google.gson.internal.bind;
import com.google.gson.TypeAdapter; import com.google.gson.TypeAdapter;

View File

@ -158,7 +158,7 @@ public final class TreeTypeAdapter<T> extends SerializationDelegatingTypeAdapter
@Override @Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
boolean matches = exactType != null boolean matches = exactType != null
? exactType.equals(type) || matchRawType && exactType.getType() == type.getRawType() ? exactType.equals(type) || (matchRawType && exactType.getType() == type.getRawType())
: hierarchyType.isAssignableFrom(type.getRawType()); : hierarchyType.isAssignableFrom(type.getRawType());
return matches return matches
? new TreeTypeAdapter<>((JsonSerializer<T>) serializer, ? new TreeTypeAdapter<>((JsonSerializer<T>) serializer,

View File

@ -42,8 +42,6 @@ import java.net.InetAddress;
import java.net.URI; import java.net.URI;
import java.net.URISyntaxException; import java.net.URISyntaxException;
import java.net.URL; import java.net.URL;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.ArrayDeque; import java.util.ArrayDeque;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.BitSet; import java.util.BitSet;
@ -124,7 +122,7 @@ public final class TypeAdapters {
@Override public void write(JsonWriter out, BitSet src) throws IOException { @Override public void write(JsonWriter out, BitSet src) throws IOException {
out.beginArray(); out.beginArray();
for (int i = 0, length = src.length(); i < length; i++) { for (int i = 0, length = src.length(); i < length; i++) {
int value = (src.get(i)) ? 1 : 0; int value = src.get(i) ? 1 : 0;
out.value(value); out.value(value);
} }
out.endArray(); out.endArray();
@ -867,24 +865,22 @@ public final class TypeAdapters {
// Uses reflection to find enum constants to work around name mismatches for obfuscated classes // Uses reflection to find enum constants to work around name mismatches for obfuscated classes
// Reflection access might throw SecurityException, therefore run this in privileged context; // Reflection access might throw SecurityException, therefore run this in privileged context;
// should be acceptable because this only retrieves enum constants, but does not expose anything else // should be acceptable because this only retrieves enum constants, but does not expose anything else
Field[] constantFields = AccessController.doPrivileged(new PrivilegedAction<Field[]>() { Field[] constantFields;
@Override public Field[] run() { {
Field[] fields = classOfT.getDeclaredFields(); Field[] fields = classOfT.getDeclaredFields();
ArrayList<Field> constantFieldsList = new ArrayList<>(fields.length); ArrayList<Field> constantFieldsList = new ArrayList<>(fields.length);
for (Field f : fields) { for (Field f : fields) {
if (f.isEnumConstant()) { if (f.isEnumConstant()) {
constantFieldsList.add(f); constantFieldsList.add(f);
}
} }
Field[] constantFields = constantFieldsList.toArray(new Field[0]);
AccessibleObject.setAccessible(constantFields, true);
return constantFields;
} }
});
constantFields = constantFieldsList.toArray(new Field[0]);
AccessibleObject.setAccessible(constantFields, true);
}
for (Field constantField : constantFields) { for (Field constantField : constantFields) {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
T constant = (T)(constantField.get(null)); T constant = (T) constantField.get(null);
String name = constant.name(); String name = constant.name();
String toStringVal = constant.toString(); String toStringVal = constant.toString();

View File

@ -1,7 +1,23 @@
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/** /**
* Do NOT use any class in this package as they are meant for internal use in Gson. * Do NOT use any class in this package as they are meant for internal use in Gson.
* These classes will very likely change incompatibly in future versions. You have been warned. * These classes will very likely change incompatibly in future versions. You have been warned.
* *
* @author Inderjeet Singh, Joel Leitch, Jesse Wilson * @author Inderjeet Singh, Joel Leitch, Jesse Wilson
*/ */
package com.google.gson.internal; package com.google.gson.internal;

View File

@ -1,3 +1,19 @@
/*
* Copyright (C) 2021 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.gson.internal.reflect; package com.google.gson.internal.reflect;
import com.google.gson.JsonIOException; import com.google.gson.JsonIOException;

View File

@ -1,3 +1,19 @@
/*
* Copyright (C) 2020 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.gson.internal.sql; package com.google.gson.internal.sql;
import com.google.gson.Gson; import com.google.gson.Gson;

View File

@ -1,3 +1,19 @@
/*
* Copyright (C) 2020 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.gson.internal.sql; package com.google.gson.internal.sql;
import java.sql.Timestamp; import java.sql.Timestamp;

View File

@ -1,3 +1,19 @@
/*
* Copyright (C) 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/** /**
* This package provides the {@link com.google.gson.Gson} class to convert Json to Java and * This package provides the {@link com.google.gson.Gson} class to convert Json to Java and
* vice-versa. * vice-versa.
@ -8,4 +24,4 @@
* *
* @author Inderjeet Singh, Joel Leitch * @author Inderjeet Singh, Joel Leitch
*/ */
package com.google.gson; package com.google.gson;

View File

@ -1,6 +1,22 @@
/*
* Copyright (C) 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/** /**
* This package provides utility classes for finding type information for generic types. * This package provides utility classes for finding type information for generic types.
* *
* @author Inderjeet Singh, Joel Leitch * @author Inderjeet Singh, Joel Leitch
*/ */
package com.google.gson.reflect; package com.google.gson.reflect;

View File

@ -37,6 +37,8 @@ import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicLong;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import com.google.gson.FormattingStyle;
/** /**
* Writes a JSON (<a href="http://www.ietf.org/rfc/rfc7159.txt">RFC 7159</a>) * Writes a JSON (<a href="http://www.ietf.org/rfc/rfc7159.txt">RFC 7159</a>)
* encoded value to a stream, one token at a time. The stream includes both * encoded value to a stream, one token at a time. The stream includes both
@ -181,10 +183,9 @@ public class JsonWriter implements Closeable, Flushable {
} }
/** /**
* A string containing a full set of spaces for a single level of * The settings used for pretty printing, or null for no pretty printing.
* indentation, or null for no pretty printing.
*/ */
private String indent; private FormattingStyle formattingStyle;
/** /**
* The name/value separator; either ":" or ": ". * The name/value separator; either ":" or ": ".
@ -224,14 +225,44 @@ public class JsonWriter implements Closeable, Flushable {
*/ */
public final void setIndent(String indent) { public final void setIndent(String indent) {
if (indent.length() == 0) { if (indent.length() == 0) {
this.indent = null; setFormattingStyle(null);
} else {
setFormattingStyle(FormattingStyle.DEFAULT.withIndent(indent));
}
}
/**
* Sets the pretty printing style to be used in the encoded document.
* No pretty printing if null.
*
* <p>Sets the various attributes to be used in the encoded document.
* For example the indentation string to be repeated for each level of indentation.
* Or the newline style, to accommodate various OS styles.</p>
*
* <p>Has no effect if the serialized format is a single line.</p>
*
* @param formattingStyle the style used for pretty printing, no pretty printing if null.
* @since $next-version$
*/
public final void setFormattingStyle(FormattingStyle formattingStyle) {
this.formattingStyle = formattingStyle;
if (formattingStyle == null) {
this.separator = ":"; this.separator = ":";
} else { } else {
this.indent = indent;
this.separator = ": "; this.separator = ": ";
} }
} }
/**
* Returns the pretty printing style used by this writer.
*
* @return the FormattingStyle that will be used.
* @since $next-version$
*/
public final FormattingStyle getFormattingStyle() {
return formattingStyle;
}
/** /**
* Configure this writer to relax its syntax rules. By default, this writer * Configure this writer to relax its syntax rules. By default, this writer
* only emits well-formed JSON as specified by <a * only emits well-formed JSON as specified by <a
@ -431,7 +462,7 @@ public class JsonWriter implements Closeable, Flushable {
private void writeDeferredComment() throws IOException { private void writeDeferredComment() throws IOException {
if (!deferredComment.isEmpty()) { if (!deferredComment.isEmpty()) {
if (indent == null) { if (formattingStyle == null || formattingStyle.getNewline().isEmpty()) {
out.append("/* ").append(String.join(" / ", deferredComment)).append(" */"); out.append("/* ").append(String.join(" / ", deferredComment)).append(" */");
} else { } else {
boolean first = true; boolean first = true;
@ -678,7 +709,7 @@ public class JsonWriter implements Closeable, Flushable {
out.close(); out.close();
int size = stackSize; int size = stackSize;
if (size > 1 || size == 1 && stack[size - 1] != NONEMPTY_DOCUMENT) { if (size > 1 || (size == 1 && stack[size - 1] != NONEMPTY_DOCUMENT)) {
throw new IOException("Incomplete document"); throw new IOException("Incomplete document");
} }
stackSize = 0; stackSize = 0;
@ -717,13 +748,13 @@ public class JsonWriter implements Closeable, Flushable {
} }
private void newline() throws IOException { private void newline() throws IOException {
if (indent == null) { if (formattingStyle == null) {
return; return;
} }
out.write('\n'); out.write(formattingStyle.getNewline());
for (int i = 1, size = stackSize; i < size; i++) { for (int i = 1, size = stackSize; i < size; i++) {
out.write(indent); out.write(formattingStyle.getIndent());
} }
} }

View File

@ -1,3 +1,19 @@
/*
* Copyright (C) 2021 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/** /**
* This package provides classes for processing JSON in an efficient streaming way. * This package provides classes for processing JSON in an efficient streaming way.
*/ */

View File

@ -1,3 +1,19 @@
/*
* Copyright (C) 2015 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.gson.util; package com.google.gson.util;
import java.text.ParseException; import java.text.ParseException;

View File

@ -1,3 +1,19 @@
/*
* Copyright (C) 2018 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/** /**
* Defines the Gson serialization/deserialization API. * Defines the Gson serialization/deserialization API.
* @since 2.8.6 * @since 2.8.6

View File

@ -1,3 +1,19 @@
/*
* Copyright (C) 2021 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.gson; package com.google.gson;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;

View File

@ -63,7 +63,8 @@ public final class GsonTest {
public void testOverridesDefaultExcluder() { public void testOverridesDefaultExcluder() {
Gson gson = new Gson(CUSTOM_EXCLUDER, CUSTOM_FIELD_NAMING_STRATEGY, Gson gson = new Gson(CUSTOM_EXCLUDER, CUSTOM_FIELD_NAMING_STRATEGY,
new HashMap<Type, InstanceCreator<?>>(), true, false, false, true, false, new HashMap<Type, InstanceCreator<?>>(), true, false, false, true, false,
true, true, false, false, true, LongSerializationPolicy.DEFAULT, null, DateFormat.DEFAULT, FormattingStyle.DEFAULT, true, false, false, true,
LongSerializationPolicy.DEFAULT, null, DateFormat.DEFAULT,
DateFormat.DEFAULT, new ArrayList<TypeAdapterFactory>(), DateFormat.DEFAULT, new ArrayList<TypeAdapterFactory>(),
new ArrayList<TypeAdapterFactory>(), new ArrayList<TypeAdapterFactory>(), new ArrayList<TypeAdapterFactory>(), new ArrayList<TypeAdapterFactory>(),
CUSTOM_OBJECT_TO_NUMBER_STRATEGY, CUSTOM_NUMBER_TO_NUMBER_STRATEGY, CUSTOM_OBJECT_TO_NUMBER_STRATEGY, CUSTOM_NUMBER_TO_NUMBER_STRATEGY,
@ -79,7 +80,8 @@ public final class GsonTest {
public void testClonedTypeAdapterFactoryListsAreIndependent() { public void testClonedTypeAdapterFactoryListsAreIndependent() {
Gson original = new Gson(CUSTOM_EXCLUDER, CUSTOM_FIELD_NAMING_STRATEGY, Gson original = new Gson(CUSTOM_EXCLUDER, CUSTOM_FIELD_NAMING_STRATEGY,
new HashMap<Type, InstanceCreator<?>>(), true, false, false, true, false, new HashMap<Type, InstanceCreator<?>>(), true, false, false, true, false,
true, true, false, false, true, LongSerializationPolicy.DEFAULT, null, DateFormat.DEFAULT, FormattingStyle.DEFAULT, true, false, false, true,
LongSerializationPolicy.DEFAULT, null, DateFormat.DEFAULT,
DateFormat.DEFAULT, new ArrayList<TypeAdapterFactory>(), DateFormat.DEFAULT, new ArrayList<TypeAdapterFactory>(),
new ArrayList<TypeAdapterFactory>(), new ArrayList<TypeAdapterFactory>(), new ArrayList<TypeAdapterFactory>(), new ArrayList<TypeAdapterFactory>(),
CUSTOM_OBJECT_TO_NUMBER_STRATEGY, CUSTOM_NUMBER_TO_NUMBER_STRATEGY, CUSTOM_OBJECT_TO_NUMBER_STRATEGY, CUSTOM_NUMBER_TO_NUMBER_STRATEGY,

View File

@ -1,3 +1,19 @@
/*
* Copyright (C) 2022 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.gson; package com.google.gson;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
@ -202,9 +218,9 @@ public class JsonArrayAsListTest {
a.add(1); a.add(1);
List<JsonElement> list = a.asList(); List<JsonElement> list = a.asList();
assertThat(list.contains(new JsonPrimitive(1))).isTrue(); assertThat(list).contains(new JsonPrimitive(1));
assertThat(list.contains(new JsonPrimitive(2))).isFalse(); assertThat(list).doesNotContain(new JsonPrimitive(2));
assertThat(list.contains(null)).isFalse(); assertThat(list).doesNotContain(null);
@SuppressWarnings({"unlikely-arg-type", "CollectionIncompatibleType"}) @SuppressWarnings({"unlikely-arg-type", "CollectionIncompatibleType"})
boolean containsInt = list.contains(1); // should only contain JsonPrimitive(1) boolean containsInt = list.contains(1); // should only contain JsonPrimitive(1)

View File

@ -20,6 +20,7 @@ import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage; import static com.google.common.truth.Truth.assertWithMessage;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import com.google.common.testing.EqualsTester;
import com.google.gson.common.MoreAsserts; import com.google.gson.common.MoreAsserts;
import java.math.BigInteger; import java.math.BigInteger;
import org.junit.Test; import org.junit.Test;
@ -39,7 +40,7 @@ public final class JsonArrayTest {
JsonArray a = new JsonArray(); JsonArray a = new JsonArray();
JsonArray b = new JsonArray(); JsonArray b = new JsonArray();
assertThat(a).isEqualTo(a); new EqualsTester().addEqualityGroup(a).testEquals();
a.add(new JsonObject()); a.add(new JsonObject());
assertThat(a.equals(b)).isFalse(); assertThat(a.equals(b)).isFalse();
@ -67,12 +68,12 @@ public final class JsonArrayTest {
JsonPrimitive a = new JsonPrimitive("a"); JsonPrimitive a = new JsonPrimitive("a");
array.add(a); array.add(a);
assertThat(array.remove(a)).isTrue(); assertThat(array.remove(a)).isTrue();
assertThat(array.contains(a)).isFalse(); assertThat(array).doesNotContain(a);
array.add(a); array.add(a);
array.add(new JsonPrimitive("b")); array.add(new JsonPrimitive("b"));
assertThat(array.remove(1).getAsString()).isEqualTo("b"); assertThat(array.remove(1).getAsString()).isEqualTo("b");
assertThat(array).hasSize(1); assertThat(array).hasSize(1);
assertThat(array.contains(a)).isTrue(); assertThat(array).contains(a);
} }
@Test @Test

View File

@ -1,3 +1,19 @@
/*
* Copyright (C) 2022 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.gson; package com.google.gson;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;

View File

@ -19,6 +19,7 @@ package com.google.gson;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import com.google.common.testing.EqualsTester;
import com.google.gson.common.MoreAsserts; import com.google.gson.common.MoreAsserts;
import java.util.AbstractMap.SimpleEntry; import java.util.AbstractMap.SimpleEntry;
import java.util.ArrayDeque; import java.util.ArrayDeque;
@ -167,7 +168,7 @@ public class JsonObjectTest {
JsonObject a = new JsonObject(); JsonObject a = new JsonObject();
JsonObject b = new JsonObject(); JsonObject b = new JsonObject();
assertThat(a).isEqualTo(a); new EqualsTester().addEqualityGroup(a).testEquals();
a.add("foo", new JsonObject()); a.add("foo", new JsonObject());
assertThat(a.equals(b)).isFalse(); assertThat(a.equals(b)).isFalse();
@ -255,8 +256,7 @@ public class JsonObjectTest {
assertThat(a.size()).isEqualTo(2); assertThat(a.size()).isEqualTo(2);
assertThat(a.keySet()).hasSize(2); assertThat(a.keySet()).hasSize(2);
assertThat(a.keySet().contains("foo")).isTrue(); assertThat(a.keySet()).containsExactly("foo", "bar").inOrder();
assertThat(a.keySet().contains("bar")).isTrue();
a.addProperty("1", true); a.addProperty("1", true);
a.addProperty("2", false); a.addProperty("2", false);

View File

@ -1,3 +1,19 @@
/*
* Copyright (C) 2022 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.gson; package com.google.gson;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;

View File

@ -300,10 +300,8 @@ public class JsonPrimitiveTest {
@Test @Test
public void testEqualsIntegerAndBigInteger() { public void testEqualsIntegerAndBigInteger() {
JsonPrimitive a = new JsonPrimitive(5L); JsonPrimitive a = new JsonPrimitive(5L);
JsonPrimitive b = new JsonPrimitive(new BigInteger("18446744073709551621")); // 2^64 + 5 JsonPrimitive b = new JsonPrimitive(new BigInteger("18446744073709551621"));
// Ideally, the following assertion should have failed but the price is too much to pay assertWithMessage("%s not equals %s", a, b).that(a.equals(b)).isFalse();
// assertFalse(a + " equals " + b, a.equals(b));
assertWithMessage("%s equals %s", a, b).that(a.equals(b)).isTrue();
} }
@Test @Test

View File

@ -1,3 +1,19 @@
/*
* Copyright (C) 2022 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.gson; package com.google.gson;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;

View File

@ -1,3 +1,19 @@
/*
* Copyright (C) 2022 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.gson; package com.google.gson;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;

View File

@ -227,7 +227,8 @@ public class TestTypes {
} }
} }
@SuppressWarnings("overrides") // for missing hashCode() override // for missing hashCode() override
@SuppressWarnings({"overrides", "EqualsHashCode"})
public static class ClassWithNoFields { public static class ClassWithNoFields {
// Nothing here.. // Nothing here..
@Override @Override

View File

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

View File

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

View File

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

View File

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

View File

@ -16,8 +16,7 @@
package com.google.gson.functional; package com.google.gson.functional;
import static org.junit.Assert.assertEquals; import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertNull;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;
@ -50,21 +49,21 @@ public class CustomDeserializerTest {
} }
@Test @Test
public void testDefaultConstructorNotCalledOnObject() throws Exception { public void testDefaultConstructorNotCalledOnObject() {
DataHolder data = new DataHolder(DEFAULT_VALUE); DataHolder data = new DataHolder(DEFAULT_VALUE);
String json = gson.toJson(data); String json = gson.toJson(data);
DataHolder actual = gson.fromJson(json, DataHolder.class); DataHolder actual = gson.fromJson(json, DataHolder.class);
assertEquals(DEFAULT_VALUE + SUFFIX, actual.getData()); assertThat(actual.getData()).isEqualTo(DEFAULT_VALUE + SUFFIX);
} }
@Test @Test
public void testDefaultConstructorNotCalledOnField() throws Exception { public void testDefaultConstructorNotCalledOnField() {
DataHolderWrapper dataWrapper = new DataHolderWrapper(new DataHolder(DEFAULT_VALUE)); DataHolderWrapper dataWrapper = new DataHolderWrapper(new DataHolder(DEFAULT_VALUE));
String json = gson.toJson(dataWrapper); String json = gson.toJson(dataWrapper);
DataHolderWrapper actual = gson.fromJson(json, DataHolderWrapper.class); DataHolderWrapper actual = gson.fromJson(json, DataHolderWrapper.class);
assertEquals(DEFAULT_VALUE + SUFFIX, actual.getWrappedData().getData()); assertThat(actual.getWrappedData().getData()).isEqualTo(DEFAULT_VALUE + SUFFIX);
} }
private static class DataHolder { private static class DataHolder {
@ -123,7 +122,7 @@ public class CustomDeserializerTest {
return context.deserialize(json1, SubTypes.valueOf(type).getSubclass()); return context.deserialize(json1, SubTypes.valueOf(type).getSubclass());
}).create(); }).create();
SubType1 target = (SubType1) gson.fromJson(json, MyBase.class); SubType1 target = (SubType1) gson.fromJson(json, MyBase.class);
assertEquals("abc", target.field1); assertThat(target.field1).isEqualTo("abc");
} }
private static class MyBase { private static class MyBase {
@ -158,7 +157,7 @@ public class CustomDeserializerTest {
.registerTypeAdapter(Base.class, (JsonDeserializer<Base>) (json, typeOfT, context) -> null).create(); .registerTypeAdapter(Base.class, (JsonDeserializer<Base>) (json, typeOfT, context) -> null).create();
String json = "{baseName:'Base',subName:'SubRevised'}"; String json = "{baseName:'Base',subName:'SubRevised'}";
Base target = gson.fromJson(json, Base.class); Base target = gson.fromJson(json, Base.class);
assertNull(target); assertThat(target).isNull();
} }
@Test @Test
@ -168,7 +167,7 @@ public class CustomDeserializerTest {
.registerTypeAdapter(Base.class, (JsonDeserializer<Base>) (json, typeOfT, context) -> null).create(); .registerTypeAdapter(Base.class, (JsonDeserializer<Base>) (json, typeOfT, context) -> null).create();
String json = "{base:{baseName:'Base',subName:'SubRevised'}}"; String json = "{base:{baseName:'Base',subName:'SubRevised'}}";
ClassWithBaseField target = gson.fromJson(json, ClassWithBaseField.class); ClassWithBaseField target = gson.fromJson(json, ClassWithBaseField.class);
assertNull(target.base); assertThat(target.base).isNull();
} }
@Test @Test
@ -178,8 +177,8 @@ public class CustomDeserializerTest {
.registerTypeAdapter(Base.class, (JsonDeserializer<Base>) (json, typeOfT, context) -> null).create(); .registerTypeAdapter(Base.class, (JsonDeserializer<Base>) (json, typeOfT, context) -> null).create();
String json = "[{baseName:'Base'},{baseName:'Base'}]"; String json = "[{baseName:'Base'},{baseName:'Base'}]";
Base[] target = gson.fromJson(json, Base[].class); Base[] target = gson.fromJson(json, Base[].class);
assertNull(target[0]); assertThat(target[0]).isNull();
assertNull(target[1]); assertThat(target[1]).isNull();
} }
@Test @Test
@ -189,8 +188,8 @@ public class CustomDeserializerTest {
.registerTypeAdapter(Base.class, (JsonDeserializer<Base>) (json, typeOfT, context) -> null).create(); .registerTypeAdapter(Base.class, (JsonDeserializer<Base>) (json, typeOfT, context) -> null).create();
String json = "{bases:[{baseName:'Base'},{baseName:'Base'}]}"; String json = "{bases:[{baseName:'Base'},{baseName:'Base'}]}";
ClassWithBaseArray target = gson.fromJson(json, ClassWithBaseArray.class); ClassWithBaseArray target = gson.fromJson(json, ClassWithBaseArray.class);
assertNull(target.bases[0]); assertThat(target.bases[0]).isNull();
assertNull(target.bases[1]); assertThat(target.bases[1]).isNull();
} }
private static final class ClassWithBaseArray { private static final class ClassWithBaseArray {

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -0,0 +1,152 @@
/*
* Copyright (C) 2022 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.gson.functional;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import com.google.gson.FormattingStyle;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* Functional tests for formatting styles.
*
* @author Mihai Nita
*/
@RunWith(JUnit4.class)
public class FormattingStyleTest {
private static final String[] INPUT = {"v1", "v2"};
private static final String EXPECTED = "[<EOL><INDENT>\"v1\",<EOL><INDENT>\"v2\"<EOL>]";
private static final String EXPECTED_OS = buildExpected(System.lineSeparator(), " ");
private static final String EXPECTED_CR = buildExpected("\r", " ");
private static final String EXPECTED_LF = buildExpected("\n", " ");
private static final String EXPECTED_CRLF = buildExpected("\r\n", " ");
// Various valid strings that can be used for newline and indent
private static final String[] TEST_NEWLINES = {
"", "\r", "\n", "\r\n", "\n\r\r\n", System.lineSeparator()
};
private static final String[] TEST_INDENTS = {
"", " ", " ", " ", "\t", " \t \t"
};
@Test
public void testDefault() {
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json = gson.toJson(INPUT);
// Make sure the default uses LF, like before.
assertEquals(EXPECTED_LF, json);
}
@Test
public void testNewlineCrLf() {
FormattingStyle style = FormattingStyle.DEFAULT.withNewline("\r\n");
Gson gson = new GsonBuilder().setPrettyPrinting(style).create();
String json = gson.toJson(INPUT);
assertEquals(EXPECTED_CRLF, json);
}
@Test
public void testNewlineLf() {
FormattingStyle style = FormattingStyle.DEFAULT.withNewline("\n");
Gson gson = new GsonBuilder().setPrettyPrinting(style).create();
String json = gson.toJson(INPUT);
assertEquals(EXPECTED_LF, json);
}
@Test
public void testNewlineCr() {
FormattingStyle style = FormattingStyle.DEFAULT.withNewline("\r");
Gson gson = new GsonBuilder().setPrettyPrinting(style).create();
String json = gson.toJson(INPUT);
assertEquals(EXPECTED_CR, json);
}
@Test
public void testNewlineOs() {
FormattingStyle style = FormattingStyle.DEFAULT.withNewline(System.lineSeparator());
Gson gson = new GsonBuilder().setPrettyPrinting(style).create();
String json = gson.toJson(INPUT);
assertEquals(EXPECTED_OS, json);
}
@Test
public void testVariousCombinationsToString() {
for (String indent : TEST_INDENTS) {
for (String newline : TEST_NEWLINES) {
FormattingStyle style = FormattingStyle.DEFAULT.withNewline(newline).withIndent(indent);
Gson gson = new GsonBuilder().setPrettyPrinting(style).create();
String json = gson.toJson(INPUT);
assertEquals(buildExpected(newline, indent), json);
}
}
}
@Test
public void testVariousCombinationsParse() {
// Mixing various indent and newline styles in the same string, to be parsed.
String jsonStringMix = "[\r\t'v1',\r\n 'v2'\n]";
String[] actualParsed;
// Test all that all combinations of newline can be parsed and generate the same INPUT.
for (String indent : TEST_INDENTS) {
for (String newline : TEST_NEWLINES) {
FormattingStyle style = FormattingStyle.DEFAULT.withNewline(newline).withIndent(indent);
Gson gson = new GsonBuilder().setLenient().setPrettyPrinting(style).create();
String toParse = buildExpected(newline, indent);
actualParsed = gson.fromJson(toParse, INPUT.getClass());
assertArrayEquals(INPUT, actualParsed);
// Parse the mixed string with the gson parsers configured with various newline / indents.
actualParsed = gson.fromJson(jsonStringMix, INPUT.getClass());
assertArrayEquals(INPUT, actualParsed);
}
}
}
@Test
public void testStyleValidations() {
try {
// TBD if we want to accept \u2028 and \u2029. For now we don't.
FormattingStyle.DEFAULT.withNewline("\u2028");
fail("Gson should not accept anything but \\r and \\n for newline");
} catch (IllegalArgumentException expected) {
}
try {
FormattingStyle.DEFAULT.withNewline("NL");
fail("Gson should not accept anything but \\r and \\n for newline");
} catch (IllegalArgumentException expected) {
}
try {
FormattingStyle.DEFAULT.withIndent("\f");
fail("Gson should not accept anything but space and tab for indent");
} catch (IllegalArgumentException expected) {
}
}
private static String buildExpected(String newline, String indent) {
return EXPECTED.replace("<EOL>", newline).replace("<INDENT>", indent);
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,8 +1,22 @@
/*
* Copyright (C) 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.gson.functional; package com.google.gson.functional;
import static org.junit.Assert.assertEquals; import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import com.google.gson.Gson; import com.google.gson.Gson;
@ -35,10 +49,10 @@ public class JsonTreeTest {
public void testToJsonTree() { public void testToJsonTree() {
BagOfPrimitives bag = new BagOfPrimitives(10L, 5, false, "foo"); BagOfPrimitives bag = new BagOfPrimitives(10L, 5, false, "foo");
JsonElement json = gson.toJsonTree(bag); JsonElement json = gson.toJsonTree(bag);
assertTrue(json.isJsonObject()); assertThat(json.isJsonObject()).isTrue();
JsonObject obj = json.getAsJsonObject(); JsonObject obj = json.getAsJsonObject();
Set<Entry<String, JsonElement>> children = obj.entrySet(); Set<Entry<String, JsonElement>> children = obj.entrySet();
assertEquals(4, children.size()); assertThat(children).hasSize(4);
assertContains(obj, new JsonPrimitive(10L)); assertContains(obj, new JsonPrimitive(10L));
assertContains(obj, new JsonPrimitive(5)); assertContains(obj, new JsonPrimitive(5));
assertContains(obj, new JsonPrimitive(false)); assertContains(obj, new JsonPrimitive(false));
@ -49,10 +63,10 @@ public class JsonTreeTest {
public void testToJsonTreeObjectType() { public void testToJsonTreeObjectType() {
SubTypeOfBagOfPrimitives bag = new SubTypeOfBagOfPrimitives(10L, 5, false, "foo", 1.4F); SubTypeOfBagOfPrimitives bag = new SubTypeOfBagOfPrimitives(10L, 5, false, "foo", 1.4F);
JsonElement json = gson.toJsonTree(bag, BagOfPrimitives.class); JsonElement json = gson.toJsonTree(bag, BagOfPrimitives.class);
assertTrue(json.isJsonObject()); assertThat(json.isJsonObject()).isTrue();
JsonObject obj = json.getAsJsonObject(); JsonObject obj = json.getAsJsonObject();
Set<Entry<String, JsonElement>> children = obj.entrySet(); Set<Entry<String, JsonElement>> children = obj.entrySet();
assertEquals(4, children.size()); assertThat(children).hasSize(4);
assertContains(obj, new JsonPrimitive(10L)); assertContains(obj, new JsonPrimitive(10L));
assertContains(obj, new JsonPrimitive(5)); assertContains(obj, new JsonPrimitive(5));
assertContains(obj, new JsonPrimitive(false)); assertContains(obj, new JsonPrimitive(false));
@ -65,14 +79,14 @@ public class JsonTreeTest {
String json1 = gson.toJson(bag); String json1 = gson.toJson(bag);
JsonElement jsonElement = gson.toJsonTree(bag, SubTypeOfBagOfPrimitives.class); JsonElement jsonElement = gson.toJsonTree(bag, SubTypeOfBagOfPrimitives.class);
String json2 = gson.toJson(jsonElement); String json2 = gson.toJson(jsonElement);
assertEquals(json1, json2); assertThat(json2).isEqualTo(json1);
} }
@Test @Test
public void testJsonTreeNull() { public void testJsonTreeNull() {
BagOfPrimitives bag = new BagOfPrimitives(10L, 5, false, null); BagOfPrimitives bag = new BagOfPrimitives(10L, 5, false, null);
JsonObject jsonElement = (JsonObject) gson.toJsonTree(bag, BagOfPrimitives.class); JsonObject jsonElement = (JsonObject) gson.toJsonTree(bag, BagOfPrimitives.class);
assertFalse(jsonElement.has("stringValue")); assertThat(jsonElement.has("stringValue")).isFalse();
} }
private void assertContains(JsonObject json, JsonPrimitive child) { private void assertContains(JsonObject json, JsonPrimitive child) {

View File

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

View File

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

View File

@ -16,10 +16,7 @@
package com.google.gson.functional; package com.google.gson.functional;
import static org.junit.Assert.assertEquals; import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import com.google.gson.Gson; import com.google.gson.Gson;
@ -71,8 +68,8 @@ public class MapTest {
map.put("b", 2); map.put("b", 2);
Type typeOfMap = new TypeToken<Map<String, Integer>>() {}.getType(); Type typeOfMap = new TypeToken<Map<String, Integer>>() {}.getType();
String json = gson.toJson(map, typeOfMap); String json = gson.toJson(map, typeOfMap);
assertTrue(json.contains("\"a\":1")); assertThat(json).contains("\"a\":1");
assertTrue(json.contains("\"b\":2")); assertThat(json).contains("\"b\":2");
} }
@Test @Test
@ -80,8 +77,8 @@ public class MapTest {
String json = "{\"a\":1,\"b\":2}"; String json = "{\"a\":1,\"b\":2}";
Type typeOfMap = new TypeToken<Map<String,Integer>>(){}.getType(); Type typeOfMap = new TypeToken<Map<String,Integer>>(){}.getType();
Map<String, Integer> target = gson.fromJson(json, typeOfMap); Map<String, Integer> target = gson.fromJson(json, typeOfMap);
assertEquals(1, target.get("a").intValue()); assertThat(target.get("a")).isEqualTo(1);
assertEquals(2, target.get("b").intValue()); assertThat(target.get("b")).isEqualTo(2);
} }
@Test @Test
@ -92,8 +89,8 @@ public class MapTest {
Type typeOfMap = new TypeToken<Map<String,Integer>>(){}.getType(); Type typeOfMap = new TypeToken<Map<String,Integer>>(){}.getType();
String json = "{\"a\":1,\"b\":2,\"b\":3}"; String json = "{\"a\":1,\"b\":2,\"b\":3}";
Map<String,Integer> target = gsonWithDuplicateKeys.fromJson(json, typeOfMap); Map<String,Integer> target = gsonWithDuplicateKeys.fromJson(json, typeOfMap);
assertEquals(1, target.get("a").intValue()); assertThat(target.get("a")).isEqualTo(1);
assertEquals(3, target.get("b").intValue()); assertThat(target.get("b")).isEqualTo(3);
} }
@Test @Test
@ -102,8 +99,8 @@ public class MapTest {
map.put("a", 1); map.put("a", 1);
map.put("b", "string"); map.put("b", "string");
String json = gson.toJson(map); String json = gson.toJson(map);
assertTrue(json.contains("\"a\":1")); assertThat(json).contains("\"a\":1");
assertTrue(json.contains("\"b\":\"string\"")); assertThat(json).contains("\"b\":\"string\"");
} }
@Test @Test
@ -111,14 +108,14 @@ public class MapTest {
Map<String, Integer> map = new LinkedHashMap<>(); Map<String, Integer> map = new LinkedHashMap<>();
Type typeOfMap = new TypeToken<Map<String, Integer>>() {}.getType(); Type typeOfMap = new TypeToken<Map<String, Integer>>() {}.getType();
String json = gson.toJson(map, typeOfMap); String json = gson.toJson(map, typeOfMap);
assertEquals("{}", json); assertThat(json).isEqualTo("{}");
} }
@Test @Test
public void testMapDeserializationEmpty() { public void testMapDeserializationEmpty() {
Type typeOfMap = new TypeToken<Map<String, Integer>>() {}.getType(); Type typeOfMap = new TypeToken<Map<String, Integer>>() {}.getType();
Map<String, Integer> map = gson.fromJson("{}", typeOfMap); Map<String, Integer> map = gson.fromJson("{}", typeOfMap);
assertTrue(map.isEmpty()); assertThat(map).isEmpty();
} }
@Test @Test
@ -129,15 +126,15 @@ public class MapTest {
String json = gson.toJson(map, typeOfMap); String json = gson.toJson(map, typeOfMap);
// Maps are represented as JSON objects, so ignoring null field // Maps are represented as JSON objects, so ignoring null field
assertEquals("{}", json); assertThat(json).isEqualTo("{}");
} }
@Test @Test
public void testMapDeserializationWithNullValue() { public void testMapDeserializationWithNullValue() {
Type typeOfMap = new TypeToken<Map<String, Integer>>() {}.getType(); Type typeOfMap = new TypeToken<Map<String, Integer>>() {}.getType();
Map<String, Integer> map = gson.fromJson("{\"abc\":null}", typeOfMap); Map<String, Integer> map = gson.fromJson("{\"abc\":null}", typeOfMap);
assertEquals(1, map.size()); assertThat(map).hasSize(1);
assertNull(map.get("abc")); assertThat(map.get("abc")).isNull();
} }
@Test @Test
@ -148,7 +145,7 @@ public class MapTest {
Type typeOfMap = new TypeToken<Map<String, Integer>>() {}.getType(); Type typeOfMap = new TypeToken<Map<String, Integer>>() {}.getType();
String json = gson.toJson(map, typeOfMap); String json = gson.toJson(map, typeOfMap);
assertEquals("{\"abc\":null}", json); assertThat(json).isEqualTo("{\"abc\":null}");
} }
@Test @Test
@ -158,21 +155,21 @@ public class MapTest {
Type typeOfMap = new TypeToken<Map<String, Integer>>() {}.getType(); Type typeOfMap = new TypeToken<Map<String, Integer>>() {}.getType();
String json = gson.toJson(map, typeOfMap); String json = gson.toJson(map, typeOfMap);
assertEquals("{\"null\":123}", json); assertThat(json).isEqualTo("{\"null\":123}");
} }
@Test @Test
public void testMapDeserializationWithNullKey() { public void testMapDeserializationWithNullKey() {
Type typeOfMap = new TypeToken<Map<String, Integer>>() {}.getType(); Type typeOfMap = new TypeToken<Map<String, Integer>>() {}.getType();
Map<String, Integer> map = gson.fromJson("{\"null\":123}", typeOfMap); Map<String, Integer> map = gson.fromJson("{\"null\":123}", typeOfMap);
assertEquals(1, map.size()); assertThat(map).hasSize(1);
assertEquals(123, map.get("null").intValue()); assertThat(map.get("null")).isEqualTo(123);
assertNull(map.get(null)); assertThat(map.get(null)).isNull();
map = gson.fromJson("{'null':123}", typeOfMap); map = gson.fromJson("{'null':123}", typeOfMap);
assertEquals(1, map.size()); assertThat(map).hasSize(1);
assertEquals(123, map.get("null").intValue()); assertThat(map.get("null")).isEqualTo(123);
assertNull(map.get(null)); assertThat(map.get(null)).isNull();
} }
@Test @Test
@ -182,25 +179,25 @@ public class MapTest {
Type typeOfMap = new TypeToken<Map<Integer, String>>() {}.getType(); Type typeOfMap = new TypeToken<Map<Integer, String>>() {}.getType();
String json = gson.toJson(map, typeOfMap); String json = gson.toJson(map, typeOfMap);
assertEquals("{\"123\":\"456\"}", json); assertThat(json).isEqualTo("{\"123\":\"456\"}");
} }
@Test @Test
public void testMapDeserializationWithIntegerKeys() { public void testMapDeserializationWithIntegerKeys() {
Type typeOfMap = new TypeToken<Map<Integer, String>>() {}.getType(); Type typeOfMap = new TypeToken<Map<Integer, String>>() {}.getType();
Map<Integer, String> map = gson.fromJson("{\"123\":\"456\"}", typeOfMap); Map<Integer, String> map = gson.fromJson("{\"123\":\"456\"}", typeOfMap);
assertEquals(1, map.size()); assertThat(map).hasSize(1);
assertTrue(map.containsKey(123)); assertThat(map).containsKey(123);
assertEquals("456", map.get(123)); assertThat(map.get(123)).isEqualTo("456");
} }
@Test @Test
public void testMapDeserializationWithUnquotedIntegerKeys() { public void testMapDeserializationWithUnquotedIntegerKeys() {
Type typeOfMap = new TypeToken<Map<Integer, String>>() {}.getType(); Type typeOfMap = new TypeToken<Map<Integer, String>>() {}.getType();
Map<Integer, String> map = gson.fromJson("{123:\"456\"}", typeOfMap); Map<Integer, String> map = gson.fromJson("{123:\"456\"}", typeOfMap);
assertEquals(1, map.size()); assertThat(map).hasSize(1);
assertTrue(map.containsKey(123)); assertThat(map).containsKey(123);
assertEquals("456", map.get(123)); assertThat(map.get(123)).isEqualTo("456");
} }
@Test @Test
@ -209,9 +206,9 @@ public class MapTest {
String json = String.format("{\"%d\":\"456\"}", longValue); String json = String.format("{\"%d\":\"456\"}", longValue);
Type typeOfMap = new TypeToken<Map<Long, String>>() {}.getType(); Type typeOfMap = new TypeToken<Map<Long, String>>() {}.getType();
Map<Long, String> map = gson.fromJson(json, typeOfMap); Map<Long, String> map = gson.fromJson(json, typeOfMap);
assertEquals(1, map.size()); assertThat(map).hasSize(1);
assertTrue(map.containsKey(longValue)); assertThat(map).containsKey(longValue);
assertEquals("456", map.get(longValue)); assertThat(map.get(longValue)).isEqualTo("456");
} }
@Test @Test
@ -220,71 +217,71 @@ public class MapTest {
String json = String.format("{%d:\"456\"}", longKey); String json = String.format("{%d:\"456\"}", longKey);
Type typeOfMap = new TypeToken<Map<Long, String>>() {}.getType(); Type typeOfMap = new TypeToken<Map<Long, String>>() {}.getType();
Map<Long, String> map = gson.fromJson(json, typeOfMap); Map<Long, String> map = gson.fromJson(json, typeOfMap);
assertEquals(1, map.size()); assertThat(map).hasSize(1);
assertTrue(map.containsKey(longKey)); assertThat(map).containsKey(longKey);
assertEquals("456", map.get(longKey)); assertThat(map.get(longKey)).isEqualTo("456");
} }
@Test @Test
public void testHashMapDeserialization() throws Exception { public void testHashMapDeserialization() {
Type typeOfMap = new TypeToken<HashMap<Integer, String>>() {}.getType(); Type typeOfMap = new TypeToken<HashMap<Integer, String>>() {}.getType();
HashMap<Integer, String> map = gson.fromJson("{\"123\":\"456\"}", typeOfMap); HashMap<Integer, String> map = gson.fromJson("{\"123\":\"456\"}", typeOfMap);
assertEquals(1, map.size()); assertThat(map).hasSize(1);
assertTrue(map.containsKey(123)); assertThat(map).containsKey(123);
assertEquals("456", map.get(123)); assertThat(map.get(123)).isEqualTo("456");
} }
@Test @Test
public void testSortedMap() throws Exception { public void testSortedMap() {
Type typeOfMap = new TypeToken<SortedMap<Integer, String>>() {}.getType(); Type typeOfMap = new TypeToken<SortedMap<Integer, String>>() {}.getType();
SortedMap<Integer, String> map = gson.fromJson("{\"123\":\"456\"}", typeOfMap); SortedMap<Integer, String> map = gson.fromJson("{\"123\":\"456\"}", typeOfMap);
assertEquals(1, map.size()); assertThat(map).hasSize(1);
assertTrue(map.containsKey(123)); assertThat(map).containsKey(123);
assertEquals("456", map.get(123)); assertThat(map.get(123)).isEqualTo("456");
} }
@Test @Test
public void testConcurrentMap() throws Exception { public void testConcurrentMap() {
Type typeOfMap = new TypeToken<ConcurrentMap<Integer, String>>() {}.getType(); Type typeOfMap = new TypeToken<ConcurrentMap<Integer, String>>() {}.getType();
ConcurrentMap<Integer, String> map = gson.fromJson("{\"123\":\"456\"}", typeOfMap); ConcurrentMap<Integer, String> map = gson.fromJson("{\"123\":\"456\"}", typeOfMap);
assertEquals(1, map.size()); assertThat(map).hasSize(1);
assertTrue(map.containsKey(123)); assertThat(map).containsKey(123);
assertEquals("456", map.get(123)); assertThat(map.get(123)).isEqualTo("456");
String json = gson.toJson(map); String json = gson.toJson(map);
assertEquals("{\"123\":\"456\"}", json); assertThat(json).isEqualTo("{\"123\":\"456\"}");
} }
@Test @Test
public void testConcurrentHashMap() throws Exception { public void testConcurrentHashMap() {
Type typeOfMap = new TypeToken<ConcurrentHashMap<Integer, String>>() {}.getType(); Type typeOfMap = new TypeToken<ConcurrentHashMap<Integer, String>>() {}.getType();
ConcurrentHashMap<Integer, String> map = gson.fromJson("{\"123\":\"456\"}", typeOfMap); ConcurrentHashMap<Integer, String> map = gson.fromJson("{\"123\":\"456\"}", typeOfMap);
assertEquals(1, map.size()); assertThat(map).hasSize(1);
assertTrue(map.containsKey(123)); assertThat(map).containsKey(123);
assertEquals("456", map.get(123)); assertThat(map.get(123)).isEqualTo("456");
String json = gson.toJson(map); String json = gson.toJson(map);
assertEquals("{\"123\":\"456\"}", json); assertThat(json).isEqualTo("{\"123\":\"456\"}");
} }
@Test @Test
public void testConcurrentNavigableMap() throws Exception { public void testConcurrentNavigableMap() {
Type typeOfMap = new TypeToken<ConcurrentNavigableMap<Integer, String>>() {}.getType(); Type typeOfMap = new TypeToken<ConcurrentNavigableMap<Integer, String>>() {}.getType();
ConcurrentNavigableMap<Integer, String> map = gson.fromJson("{\"123\":\"456\"}", typeOfMap); ConcurrentNavigableMap<Integer, String> map = gson.fromJson("{\"123\":\"456\"}", typeOfMap);
assertEquals(1, map.size()); assertThat(map).hasSize(1);
assertTrue(map.containsKey(123)); assertThat(map).containsKey(123);
assertEquals("456", map.get(123)); assertThat(map.get(123)).isEqualTo("456");
String json = gson.toJson(map); String json = gson.toJson(map);
assertEquals("{\"123\":\"456\"}", json); assertThat(json).isEqualTo("{\"123\":\"456\"}");
} }
@Test @Test
public void testConcurrentSkipListMap() throws Exception { public void testConcurrentSkipListMap() {
Type typeOfMap = new TypeToken<ConcurrentSkipListMap<Integer, String>>() {}.getType(); Type typeOfMap = new TypeToken<ConcurrentSkipListMap<Integer, String>>() {}.getType();
ConcurrentSkipListMap<Integer, String> map = gson.fromJson("{\"123\":\"456\"}", typeOfMap); ConcurrentSkipListMap<Integer, String> map = gson.fromJson("{\"123\":\"456\"}", typeOfMap);
assertEquals(1, map.size()); assertThat(map).hasSize(1);
assertTrue(map.containsKey(123)); assertThat(map).containsKey(123);
assertEquals("456", map.get(123)); assertThat(map.get(123)).isEqualTo("456");
String json = gson.toJson(map); String json = gson.toJson(map);
assertEquals("{\"123\":\"456\"}", json); assertThat(json).isEqualTo("{\"123\":\"456\"}");
} }
@Test @Test
@ -293,7 +290,7 @@ public class MapTest {
map.put("a", "b"); map.put("a", "b");
Type type = new TypeToken<MyParameterizedMap<String, String>>() {}.getType(); Type type = new TypeToken<MyParameterizedMap<String, String>>() {}.getType();
String json = gson.toJson(map, type); String json = gson.toJson(map, type);
assertTrue(json.contains("\"a\":\"b\"")); assertThat(json).contains("\"a\":\"b\"");
} }
@SuppressWarnings({ "unused", "serial" }) @SuppressWarnings({ "unused", "serial" })
@ -309,16 +306,16 @@ public class MapTest {
MyMap map = new MyMap(); MyMap map = new MyMap();
map.put("a", "b"); map.put("a", "b");
String json = gson.toJson(map, MyMap.class); String json = gson.toJson(map, MyMap.class);
assertTrue(json.contains("\"a\":\"b\"")); assertThat(json).contains("\"a\":\"b\"");
} }
@Test @Test
public void testMapStandardSubclassDeserialization() { public void testMapStandardSubclassDeserialization() {
String json = "{a:'1',b:'2'}"; String json = "{a:'1',b:'2'}";
Type type = new TypeToken<LinkedHashMap<String, String>>() {}.getType(); Type type = new TypeToken<LinkedHashMap<String, String>>() {}.getType();
LinkedHashMap<String, Integer> map = gson.fromJson(json, type); LinkedHashMap<String, String> map = gson.fromJson(json, type);
assertEquals("1", map.get("a")); assertThat(map).containsEntry("a", "1");
assertEquals("2", map.get("b")); assertThat(map).containsEntry("b", "2");
} }
@Test @Test
@ -330,8 +327,8 @@ public class MapTest {
}).create(); }).create();
String json = "{\"a\":1,\"b\":2}"; String json = "{\"a\":1,\"b\":2}";
MyMap map = gson.fromJson(json, MyMap.class); MyMap map = gson.fromJson(json, MyMap.class);
assertEquals("1", map.get("a")); assertThat(map.get("a")).isEqualTo("1");
assertEquals("2", map.get("b")); assertThat(map.get("b")).isEqualTo("2");
} }
@Test @Test
@ -355,7 +352,7 @@ public class MapTest {
src.put("two", 2L); src.put("two", 2L);
src.put("three", 3L); src.put("three", 3L);
assertEquals("[1,2,3]", gson.toJson(src, type)); assertThat(gson.toJson(src, type)).isEqualTo("[1,2,3]");
} }
/** /**
@ -374,8 +371,8 @@ public class MapTest {
target.map.put("name1", null); target.map.put("name1", null);
target.map.put("name2", "value2"); target.map.put("name2", "value2");
String json = gson.toJson(target); String json = gson.toJson(target);
assertFalse(json.contains("name1")); assertThat(json).doesNotContain("name1");
assertTrue(json.contains("name2")); assertThat(json).contains("name2");
} }
/** /**
@ -388,8 +385,8 @@ public class MapTest {
target.map.put("name1", null); target.map.put("name1", null);
target.map.put("name2", "value2"); target.map.put("name2", "value2");
String json = gson.toJson(target); String json = gson.toJson(target);
assertTrue(json.contains("name1")); assertThat(json).contains("name1");
assertTrue(json.contains("name2")); assertThat(json).contains("name2");
} }
@Test @Test
@ -400,15 +397,15 @@ public class MapTest {
new TypeToken<Map<String, ? extends Collection<? extends Integer>>>() {}.getType(); new TypeToken<Map<String, ? extends Collection<? extends Integer>>>() {}.getType();
String json = gson.toJson(map, typeOfMap); String json = gson.toJson(map, typeOfMap);
assertEquals("{}", json); assertThat(json).isEqualTo("{}");
} }
@Test @Test
public void testMapDeserializationWithWildcardValues() { public void testMapDeserializationWithWildcardValues() {
Type typeOfMap = new TypeToken<Map<String, ? extends Long>>() {}.getType(); Type typeOfMap = new TypeToken<Map<String, ? extends Long>>() {}.getType();
Map<String, ? extends Long> map = gson.fromJson("{\"test\":123}", typeOfMap); Map<String, ? extends Long> map = gson.fromJson("{\"test\":123}", typeOfMap);
assertEquals(1, map.size()); assertThat(map).hasSize(1);
assertEquals(Long.valueOf(123L), map.get("test")); assertThat(map.get("test")).isEqualTo(123L);
} }
@ -430,9 +427,9 @@ public class MapTest {
nestedMap.put("2", "2"); nestedMap.put("2", "2");
map.put("nestedMap", nestedMap); map.put("nestedMap", nestedMap);
String json = gson.toJson(map); String json = gson.toJson(map);
assertTrue(json.contains("nestedMap")); assertThat(json).contains("nestedMap");
assertTrue(json.contains("\"1\":\"1\"")); assertThat(json).contains("\"1\":\"1\"");
assertTrue(json.contains("\"2\":\"2\"")); assertThat(json).contains("\"2\":\"2\"");
} }
/** /**
@ -444,8 +441,8 @@ public class MapTest {
Type type = new TypeToken<Map<String, Map<String, String>>>(){}.getType(); Type type = new TypeToken<Map<String, Map<String, String>>>(){}.getType();
Map<String, Map<String, String>> map = gson.fromJson(json, type); Map<String, Map<String, String>> map = gson.fromJson(json, type);
Map<String, String> nested = map.get("nestedMap"); Map<String, String> nested = map.get("nestedMap");
assertEquals("1", nested.get("1")); assertThat(nested.get("1")).isEqualTo("1");
assertEquals("2", nested.get("2")); assertThat(nested.get("2")).isEqualTo("2");
} }
/** /**
@ -456,7 +453,7 @@ public class MapTest {
Map<String, String> map = new HashMap<>(); Map<String, String> map = new HashMap<>();
map.put("a\"b", "c\"d"); map.put("a\"b", "c\"d");
String json = gson.toJson(map); String json = gson.toJson(map);
assertEquals("{\"a\\\"b\":\"c\\\"d\"}", json); assertThat(json).isEqualTo("{\"a\\\"b\":\"c\\\"d\"}");
} }
/** /**
@ -466,14 +463,14 @@ public class MapTest {
public void testWriteMapsWithEmptyStringKey() { public void testWriteMapsWithEmptyStringKey() {
Map<String, Boolean> map = new HashMap<>(); Map<String, Boolean> map = new HashMap<>();
map.put("", true); map.put("", true);
assertEquals("{\"\":true}", gson.toJson(map)); assertThat(gson.toJson(map)).isEqualTo("{\"\":true}");
} }
@Test @Test
public void testReadMapsWithEmptyStringKey() { public void testReadMapsWithEmptyStringKey() {
Map<String, Boolean> map = gson.fromJson("{\"\":true}", new TypeToken<Map<String, Boolean>>() {}.getType()); Map<String, Boolean> map = gson.fromJson("{\"\":true}", new TypeToken<Map<String, Boolean>>() {}.getType());
assertEquals(Boolean.TRUE, map.get("")); assertThat(map.get("")).isEqualTo(Boolean.TRUE);
} }
/** /**
@ -490,22 +487,21 @@ public class MapTest {
innerMap.put("TestStringArray", new String[] { "one", "two" }); innerMap.put("TestStringArray", new String[] { "one", "two" });
map.put("c", innerMap); map.put("c", innerMap);
assertEquals("{\"a\":12,\"b\":null,\"c\":{\"test\":1,\"TestStringArray\":[\"one\",\"two\"]}}", assertThat(new GsonBuilder().serializeNulls().create().toJson(map))
new GsonBuilder().serializeNulls().create().toJson(map)); .isEqualTo("{\"a\":12,\"b\":null,\"c\":{\"test\":1,\"TestStringArray\":[\"one\",\"two\"]}}");
assertEquals("{\n \"a\": 12,\n \"b\": null,\n \"c\": " assertThat(new GsonBuilder().setPrettyPrinting().serializeNulls().create().toJson(map))
+ "{\n \"test\": 1,\n \"TestStringArray\": " .isEqualTo("{\n \"a\": 12,\n \"b\": null,\n \"c\": "
+ "[\n \"one\",\n \"two\"\n ]\n }\n}", + "{\n \"test\": 1,\n \"TestStringArray\": "
new GsonBuilder().setPrettyPrinting().serializeNulls().create().toJson(map)); + "[\n \"one\",\n \"two\"\n ]\n }\n}");
assertEquals("{\"a\":12,\"c\":{\"test\":1,\"TestStringArray\":[\"one\",\"two\"]}}", assertThat(new GsonBuilder().create().toJson(map))
new GsonBuilder().create().toJson(map)); .isEqualTo("{\"a\":12,\"c\":{\"test\":1,\"TestStringArray\":[\"one\",\"two\"]}}");
assertEquals("{\n \"a\": 12,\n \"c\": " assertThat(new GsonBuilder().setPrettyPrinting().create().toJson(map))
+ "{\n \"test\": 1,\n \"TestStringArray\": " .isEqualTo("{\n \"a\": 12,\n \"c\": "
+ "[\n \"one\",\n \"two\"\n ]\n }\n}", + "{\n \"test\": 1,\n \"TestStringArray\": "
new GsonBuilder().setPrettyPrinting().create().toJson(map)); + "[\n \"one\",\n \"two\"\n ]\n }\n}");
innerMap.put("d", "e"); innerMap.put("d", "e");
assertEquals("{\"a\":12,\"c\":{\"test\":1,\"TestStringArray\":[\"one\",\"two\"],\"d\":\"e\"}}", assertThat(new Gson().toJson(map))
new Gson().toJson(map)); .isEqualTo("{\"a\":12,\"c\":{\"test\":1,\"TestStringArray\":[\"one\",\"two\"],\"d\":\"e\"}}");
} }
@Test @Test
@ -523,11 +519,11 @@ public class MapTest {
.enableComplexMapKeySerialization() .enableComplexMapKeySerialization()
.create(); .create();
String json = gsonWithComplexKeys.toJson(element); String json = gsonWithComplexKeys.toJson(element);
assertEquals(expected, json); assertThat(json).isEqualTo(expected);
Gson gson = new Gson(); Gson gson = new Gson();
json = gson.toJson(element); json = gson.toJson(element);
assertEquals(expected, json); assertThat(json).isEqualTo(expected);
} }
@Test @Test
@ -556,17 +552,17 @@ public class MapTest {
.registerTypeAdapter(TestTypes.Base.class, baseTypeAdapter) .registerTypeAdapter(TestTypes.Base.class, baseTypeAdapter)
.create(); .create();
String json = gson.toJson(element); String json = gson.toJson(element);
assertEquals(expected, json); assertThat(json).isEqualTo(expected);
gson = new GsonBuilder() gson = new GsonBuilder()
.registerTypeAdapter(TestTypes.Base.class, baseTypeAdapter) .registerTypeAdapter(TestTypes.Base.class, baseTypeAdapter)
.create(); .create();
json = gson.toJson(element); json = gson.toJson(element);
assertEquals(expected, json); assertThat(json).isEqualTo(expected);
} }
@Test @Test
public void testGeneralMapField() throws Exception { public void testGeneralMapField() {
MapWithGeneralMapParameters map = new MapWithGeneralMapParameters(); MapWithGeneralMapParameters map = new MapWithGeneralMapParameters();
map.map.put("string", "testString"); map.map.put("string", "testString");
map.map.put("stringArray", new String[]{"one", "two"}); map.map.put("stringArray", new String[]{"one", "two"});
@ -574,12 +570,12 @@ public class MapTest {
String expected = "{\"map\":{\"string\":\"testString\",\"stringArray\":" String expected = "{\"map\":{\"string\":\"testString\",\"stringArray\":"
+ "[\"one\",\"two\"],\"objectArray\":[1,2,\"three\"]}}"; + "[\"one\",\"two\"],\"objectArray\":[1,2,\"three\"]}}";
assertEquals(expected, gson.toJson(map)); assertThat(gson.toJson(map)).isEqualTo(expected);
gson = new GsonBuilder() gson = new GsonBuilder()
.enableComplexMapKeySerialization() .enableComplexMapKeySerialization()
.create(); .create();
assertEquals(expected, gson.toJson(map)); assertThat(gson.toJson(map)).isEqualTo(expected);
} }
@Test @Test
@ -588,8 +584,8 @@ public class MapTest {
map.put(new Point(2, 3), "a"); map.put(new Point(2, 3), "a");
map.put(new Point(5, 7), "b"); map.put(new Point(5, 7), "b");
String json = "{\"2,3\":\"a\",\"5,7\":\"b\"}"; String json = "{\"2,3\":\"a\",\"5,7\":\"b\"}";
assertEquals(json, gson.toJson(map, new TypeToken<Map<Point, String>>() {}.getType())); assertThat(gson.toJson(map, new TypeToken<Map<Point, String>>() {}.getType())).isEqualTo(json);
assertEquals(json, gson.toJson(map, Map.class)); assertThat(gson.toJson(map, Map.class)).isEqualTo(json);
} }
@Test @Test
@ -608,7 +604,7 @@ public class MapTest {
Map<String, String> map = new LinkedHashMap<>(); Map<String, String> map = new LinkedHashMap<>();
map.put("2,3", "a"); map.put("2,3", "a");
map.put("5,7", "b"); map.put("5,7", "b");
assertEquals(map, gson.fromJson(json, new TypeToken<Map<String, String>>() {}.getType())); assertThat(map).isEqualTo(gson.fromJson(json, new TypeToken<Map<String, String>>() {}.getType()));
} }
@Test @Test
@ -617,7 +613,7 @@ public class MapTest {
Map<Double, String> map = new LinkedHashMap<>(); Map<Double, String> map = new LinkedHashMap<>();
map.put(2.3, "a"); map.put(2.3, "a");
map.put(5.7, "b"); map.put(5.7, "b");
assertEquals(map, gson.fromJson(json, new TypeToken<Map<Double, String>>() {}.getType())); assertThat(map).isEqualTo(gson.fromJson(json, new TypeToken<Map<Double, String>>() {}.getType()));
} }
@Test @Test
@ -626,7 +622,7 @@ public class MapTest {
Map<Boolean, String> map = new LinkedHashMap<>(); Map<Boolean, String> map = new LinkedHashMap<>();
map.put(true, "a"); map.put(true, "a");
map.put(false, "b"); map.put(false, "b");
assertEquals(map, gson.fromJson(json, new TypeToken<Map<Boolean, String>>() {}.getType())); assertThat(map).isEqualTo(gson.fromJson(json, new TypeToken<Map<Boolean, String>>() {}.getType()));
} }
@Test @Test
@ -644,8 +640,8 @@ public class MapTest {
Map<String, Map<String, String>> map = newMap( Map<String, Map<String, String>> map = newMap(
"a", newMap("ka1", "va1", "ka2", "va2"), "a", newMap("ka1", "va1", "ka2", "va2"),
"b", newMap("kb1", "vb1", "kb2", "vb2")); "b", newMap("kb1", "vb1", "kb2", "vb2"));
assertEquals("{'a':{'ka1':'va1','ka2':'va2'},'b':{'kb1':'vb1','kb2':'vb2'}}", assertThat(gson.toJson(map, type).replace('"', '\''))
gson.toJson(map, type).replace('"', '\'')); .isEqualTo("{'a':{'ka1':'va1','ka2':'va2'},'b':{'kb1':'vb1','kb2':'vb2'}}");
} }
@Test @Test
@ -655,7 +651,7 @@ public class MapTest {
"a", newMap("ka1", "va1", "ka2", "va2"), "a", newMap("ka1", "va1", "ka2", "va2"),
"b", newMap("kb1", "vb1", "kb2", "vb2")); "b", newMap("kb1", "vb1", "kb2", "vb2"));
String json = "{'a':{'ka1':'va1','ka2':'va2'},'b':{'kb1':'vb1','kb2':'vb2'}}"; String json = "{'a':{'ka1':'va1','ka2':'va2'},'b':{'kb1':'vb1','kb2':'vb2'}}";
assertEquals(map, gson.fromJson(json, type)); assertThat(map).isEqualTo(gson.fromJson(json, type));
} }
private <K, V> Map<K, V> newMap(K key1, V value1, K key2, V value2) { private <K, V> Map<K, V> newMap(K key1, V value1, K key2, V value2) {
@ -671,7 +667,7 @@ public class MapTest {
Map<Double, String> map = new LinkedHashMap<>(); Map<Double, String> map = new LinkedHashMap<>();
map.put(2.3, "a"); map.put(2.3, "a");
JsonElement tree = JsonParser.parseString(json); JsonElement tree = JsonParser.parseString(json);
assertEquals(map, gson.fromJson(tree, new TypeToken<Map<Double, String>>() {}.getType())); assertThat(map).isEqualTo(gson.fromJson(tree, new TypeToken<Map<Double, String>>() {}.getType()));
} }
static class Point { static class Point {

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -16,10 +16,7 @@
package com.google.gson.functional; package com.google.gson.functional;
import static org.junit.Assert.assertArrayEquals; import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import com.google.gson.*; import com.google.gson.*;
@ -50,39 +47,39 @@ public class PrimitiveTest {
@Test @Test
public void testPrimitiveIntegerAutoboxedSerialization() { public void testPrimitiveIntegerAutoboxedSerialization() {
assertEquals("1", gson.toJson(1)); assertThat(gson.toJson(1)).isEqualTo("1");
} }
@Test @Test
public void testPrimitiveIntegerAutoboxedDeserialization() { public void testPrimitiveIntegerAutoboxedDeserialization() {
int expected = 1; int expected = 1;
int actual = gson.fromJson("1", int.class); int actual = gson.fromJson("1", int.class);
assertEquals(expected, actual); assertThat(actual).isEqualTo(expected);
actual = gson.fromJson("1", Integer.class); actual = gson.fromJson("1", Integer.class);
assertEquals(expected, actual); assertThat(actual).isEqualTo(expected);
} }
@Test @Test
public void testByteSerialization() { public void testByteSerialization() {
assertEquals("1", gson.toJson(1, byte.class)); assertThat(gson.toJson(1, byte.class)).isEqualTo("1");
assertEquals("1", gson.toJson(1, Byte.class)); assertThat(gson.toJson(1, Byte.class)).isEqualTo("1");
assertEquals(Byte.toString(Byte.MIN_VALUE), gson.toJson(Byte.MIN_VALUE, Byte.class)); assertThat(gson.toJson(Byte.MIN_VALUE, Byte.class)).isEqualTo(Byte.toString(Byte.MIN_VALUE));
assertEquals(Byte.toString(Byte.MAX_VALUE), gson.toJson(Byte.MAX_VALUE, Byte.class)); assertThat(gson.toJson(Byte.MAX_VALUE, Byte.class)).isEqualTo(Byte.toString(Byte.MAX_VALUE));
// Should perform narrowing conversion // Should perform narrowing conversion
assertEquals("-128", gson.toJson(128, Byte.class)); assertThat(gson.toJson(128, Byte.class)).isEqualTo("-128");
assertEquals("1", gson.toJson(1.5, Byte.class)); assertThat(gson.toJson(1.5, Byte.class)).isEqualTo("1");
} }
@Test @Test
public void testByteDeserialization() { public void testByteDeserialization() {
Byte boxed = gson.fromJson("1", Byte.class); Byte boxed = gson.fromJson("1", Byte.class);
assertEquals(1, (byte)boxed); assertThat(boxed).isEqualTo(1);
byte primitive = gson.fromJson("1", byte.class); byte primitive = gson.fromJson("1", byte.class);
assertEquals(1, primitive); assertThat(primitive).isEqualTo(1);
byte[] bytes = gson.fromJson("[-128, 0, 127, 255]", byte[].class); byte[] bytes = gson.fromJson("[-128, 0, 127, 255]", byte[].class);
assertArrayEquals(new byte[] {-128, 0, 127, -1}, bytes); assertThat(bytes).isEqualTo(new byte[] {-128, 0, 127, -1});
} }
@Test @Test
@ -91,46 +88,46 @@ public class PrimitiveTest {
gson.fromJson("-129", byte.class); gson.fromJson("-129", byte.class);
fail(); fail();
} catch (JsonSyntaxException e) { } catch (JsonSyntaxException e) {
assertEquals("Lossy conversion from -129 to byte; at path $", e.getMessage()); assertThat(e.getMessage()).isEqualTo("Lossy conversion from -129 to byte; at path $");
} }
try { try {
gson.fromJson("256", byte.class); gson.fromJson("256", byte.class);
fail(); fail();
} catch (JsonSyntaxException e) { } catch (JsonSyntaxException e) {
assertEquals("Lossy conversion from 256 to byte; at path $", e.getMessage()); assertThat(e.getMessage()).isEqualTo("Lossy conversion from 256 to byte; at path $");
} }
try { try {
gson.fromJson("2147483648", byte.class); gson.fromJson("2147483648", byte.class);
fail(); fail();
} catch (JsonSyntaxException e) { } catch (JsonSyntaxException e) {
assertEquals("java.lang.NumberFormatException: Expected an int but was 2147483648 at line 1 column 11 (char '\0') path $", e.getMessage()); assertThat(e.getMessage()).isEqualTo("java.lang.NumberFormatException: Expected an int but was 2147483648 at line 1 column 11 (char '\0') path $");
} }
} }
@Test @Test
public void testShortSerialization() { public void testShortSerialization() {
assertEquals("1", gson.toJson(1, short.class)); assertThat(gson.toJson(1, short.class)).isEqualTo("1");
assertEquals("1", gson.toJson(1, Short.class)); assertThat(gson.toJson(1, Short.class)).isEqualTo("1");
assertEquals(Short.toString(Short.MIN_VALUE), gson.toJson(Short.MIN_VALUE, Short.class)); assertThat(gson.toJson(Short.MIN_VALUE, Short.class)).isEqualTo(Short.toString(Short.MIN_VALUE));
assertEquals(Short.toString(Short.MAX_VALUE), gson.toJson(Short.MAX_VALUE, Short.class)); assertThat(gson.toJson(Short.MAX_VALUE, Short.class)).isEqualTo(Short.toString(Short.MAX_VALUE));
// Should perform widening conversion // Should perform widening conversion
assertEquals("1", gson.toJson((byte) 1, Short.class)); assertThat(gson.toJson((byte) 1, Short.class)).isEqualTo("1");
// Should perform narrowing conversion // Should perform narrowing conversion
assertEquals("-32768", gson.toJson(32768, Short.class)); assertThat(gson.toJson(32768, Short.class)).isEqualTo("-32768");
assertEquals("1", gson.toJson(1.5, Short.class)); assertThat(gson.toJson(1.5, Short.class)).isEqualTo("1");
} }
@Test @Test
public void testShortDeserialization() { public void testShortDeserialization() {
Short boxed = gson.fromJson("1", Short.class); Short boxed = gson.fromJson("1", Short.class);
assertEquals(1, (short)boxed); assertThat(boxed).isEqualTo(1);
short primitive = gson.fromJson("1", short.class); short primitive = gson.fromJson("1", short.class);
assertEquals(1, primitive); assertThat(primitive).isEqualTo(1);
short[] shorts = gson.fromJson("[-32768, 0, 32767, 65535]", short[].class); short[] shorts = gson.fromJson("[-32768, 0, 32767, 65535]", short[].class);
assertArrayEquals(new short[] {-32768, 0, 32767, -1}, shorts); assertThat(shorts).isEqualTo(new short[] {-32768, 0, 32767, -1});
} }
@Test @Test
@ -139,151 +136,151 @@ public class PrimitiveTest {
gson.fromJson("-32769", short.class); gson.fromJson("-32769", short.class);
fail(); fail();
} catch (JsonSyntaxException e) { } catch (JsonSyntaxException e) {
assertEquals("Lossy conversion from -32769 to short; at path $", e.getMessage()); assertThat(e.getMessage()).isEqualTo("Lossy conversion from -32769 to short; at path $");
} }
try { try {
gson.fromJson("65536", short.class); gson.fromJson("65536", short.class);
fail(); fail();
} catch (JsonSyntaxException e) { } catch (JsonSyntaxException e) {
assertEquals("Lossy conversion from 65536 to short; at path $", e.getMessage()); assertThat(e.getMessage()).isEqualTo("Lossy conversion from 65536 to short; at path $");
} }
try { try {
gson.fromJson("2147483648", short.class); gson.fromJson("2147483648", short.class);
fail(); fail();
} catch (JsonSyntaxException e) { } catch (JsonSyntaxException e) {
assertEquals("java.lang.NumberFormatException: Expected an int but was 2147483648 at line 1 column 11 (char '\0') path $", e.getMessage()); assertThat(e.getMessage()).isEqualTo("java.lang.NumberFormatException: Expected an int but was 2147483648 at line 1 column 11 (char '\0') path $");
} }
} }
@Test @Test
public void testIntSerialization() { public void testIntSerialization() {
assertEquals("1", gson.toJson(1, int.class)); assertThat(gson.toJson(1, int.class)).isEqualTo("1");
assertEquals("1", gson.toJson(1, Integer.class)); assertThat(gson.toJson(1, Integer.class)).isEqualTo("1");
assertEquals(Integer.toString(Integer.MIN_VALUE), gson.toJson(Integer.MIN_VALUE, Integer.class)); assertThat(gson.toJson(Integer.MIN_VALUE, Integer.class)).isEqualTo(Integer.toString(Integer.MIN_VALUE));
assertEquals(Integer.toString(Integer.MAX_VALUE), gson.toJson(Integer.MAX_VALUE, Integer.class)); assertThat(gson.toJson(Integer.MAX_VALUE, Integer.class)).isEqualTo(Integer.toString(Integer.MAX_VALUE));
// Should perform widening conversion // Should perform widening conversion
assertEquals("1", gson.toJson((byte) 1, Integer.class)); assertThat(gson.toJson((byte) 1, Integer.class)).isEqualTo("1");
// Should perform narrowing conversion // Should perform narrowing conversion
assertEquals("-2147483648", gson.toJson(2147483648L, Integer.class)); assertThat(gson.toJson(2147483648L, Integer.class)).isEqualTo("-2147483648");
assertEquals("1", gson.toJson(1.5, Integer.class)); assertThat(gson.toJson(1.5, Integer.class)).isEqualTo("1");
} }
@Test @Test
public void testLongSerialization() { public void testLongSerialization() {
assertEquals("1", gson.toJson(1L, long.class)); assertThat(gson.toJson(1L, long.class)).isEqualTo("1");
assertEquals("1", gson.toJson(1L, Long.class)); assertThat(gson.toJson(1L, Long.class)).isEqualTo("1");
assertEquals(Long.toString(Long.MIN_VALUE), gson.toJson(Long.MIN_VALUE, Long.class)); assertThat(gson.toJson(Long.MIN_VALUE, Long.class)).isEqualTo(Long.toString(Long.MIN_VALUE));
assertEquals(Long.toString(Long.MAX_VALUE), gson.toJson(Long.MAX_VALUE, Long.class)); assertThat(gson.toJson(Long.MAX_VALUE, Long.class)).isEqualTo(Long.toString(Long.MAX_VALUE));
// Should perform widening conversion // Should perform widening conversion
assertEquals("1", gson.toJson((byte) 1, Long.class)); assertThat(gson.toJson((byte) 1, Long.class)).isEqualTo("1");
// Should perform narrowing conversion // Should perform narrowing conversion
assertEquals("1", gson.toJson(1.5, Long.class)); assertThat(gson.toJson(1.5, Long.class)).isEqualTo("1");
} }
@Test @Test
public void testFloatSerialization() { public void testFloatSerialization() {
assertEquals("1.5", gson.toJson(1.5f, float.class)); assertThat(gson.toJson(1.5f, float.class)).isEqualTo("1.5");
assertEquals("1.5", gson.toJson(1.5f, Float.class)); assertThat(gson.toJson(1.5f, Float.class)).isEqualTo("1.5");
assertEquals(Float.toString(Float.MIN_VALUE), gson.toJson(Float.MIN_VALUE, Float.class)); assertThat(gson.toJson(Float.MIN_VALUE, Float.class)).isEqualTo(Float.toString(Float.MIN_VALUE));
assertEquals(Float.toString(Float.MAX_VALUE), gson.toJson(Float.MAX_VALUE, Float.class)); assertThat(gson.toJson(Float.MAX_VALUE, Float.class)).isEqualTo(Float.toString(Float.MAX_VALUE));
// Should perform widening conversion // Should perform widening conversion
assertEquals("1.0", gson.toJson((byte) 1, Float.class)); assertThat(gson.toJson((byte) 1, Float.class)).isEqualTo("1.0");
// (This widening conversion is actually lossy) // (This widening conversion is actually lossy)
assertEquals(Float.toString(Long.MAX_VALUE - 10L), gson.toJson(Long.MAX_VALUE - 10L, Float.class)); assertThat(gson.toJson(Long.MAX_VALUE - 10L, Float.class)).isEqualTo(Float.toString(Long.MAX_VALUE - 10L));
// Should perform narrowing conversion // Should perform narrowing conversion
gson = new GsonBuilder().serializeSpecialFloatingPointValues().create(); gson = new GsonBuilder().serializeSpecialFloatingPointValues().create();
assertEquals("Infinity", gson.toJson(Double.MAX_VALUE, Float.class)); assertThat(gson.toJson(Double.MAX_VALUE, Float.class)).isEqualTo("Infinity");
} }
@Test @Test
public void testDoubleSerialization() { public void testDoubleSerialization() {
assertEquals("1.5", gson.toJson(1.5, double.class)); assertThat(gson.toJson(1.5, double.class)).isEqualTo("1.5");
assertEquals("1.5", gson.toJson(1.5, Double.class)); assertThat(gson.toJson(1.5, Double.class)).isEqualTo("1.5");
assertEquals(Double.toString(Double.MIN_VALUE), gson.toJson(Double.MIN_VALUE, Double.class)); assertThat(gson.toJson(Double.MIN_VALUE, Double.class)).isEqualTo(Double.toString(Double.MIN_VALUE));
assertEquals(Double.toString(Double.MAX_VALUE), gson.toJson(Double.MAX_VALUE, Double.class)); assertThat(gson.toJson(Double.MAX_VALUE, Double.class)).isEqualTo(Double.toString(Double.MAX_VALUE));
// Should perform widening conversion // Should perform widening conversion
assertEquals("1.0", gson.toJson((byte) 1, Double.class)); assertThat(gson.toJson((byte) 1, Double.class)).isEqualTo("1.0");
// (This widening conversion is actually lossy) // (This widening conversion is actually lossy)
assertEquals(Double.toString(Long.MAX_VALUE - 10L), gson.toJson(Long.MAX_VALUE - 10L, Double.class)); assertThat(gson.toJson(Long.MAX_VALUE - 10L, Double.class)).isEqualTo(Double.toString(Long.MAX_VALUE - 10L));
} }
@Test @Test
public void testPrimitiveIntegerAutoboxedInASingleElementArraySerialization() { public void testPrimitiveIntegerAutoboxedInASingleElementArraySerialization() {
int target[] = {-9332}; int[] target = {-9332};
assertEquals("[-9332]", gson.toJson(target)); assertThat(gson.toJson(target)).isEqualTo("[-9332]");
assertEquals("[-9332]", gson.toJson(target, int[].class)); assertThat(gson.toJson(target, int[].class)).isEqualTo("[-9332]");
assertEquals("[-9332]", gson.toJson(target, Integer[].class)); assertThat(gson.toJson(target, Integer[].class)).isEqualTo("[-9332]");
} }
@Test @Test
public void testReallyLongValuesSerialization() { public void testReallyLongValuesSerialization() {
long value = 333961828784581L; long value = 333961828784581L;
assertEquals("333961828784581", gson.toJson(value)); assertThat(gson.toJson(value)).isEqualTo("333961828784581");
} }
@Test @Test
public void testReallyLongValuesDeserialization() { public void testReallyLongValuesDeserialization() {
String json = "333961828784581"; String json = "333961828784581";
long value = gson.fromJson(json, Long.class); long value = gson.fromJson(json, Long.class);
assertEquals(333961828784581L, value); assertThat(value).isEqualTo(333961828784581L);
} }
@Test @Test
public void testPrimitiveLongAutoboxedSerialization() { public void testPrimitiveLongAutoboxedSerialization() {
assertEquals("1", gson.toJson(1L, long.class)); assertThat(gson.toJson(1L, long.class)).isEqualTo("1");
assertEquals("1", gson.toJson(1L, Long.class)); assertThat(gson.toJson(1L, Long.class)).isEqualTo("1");
} }
@Test @Test
public void testPrimitiveLongAutoboxedDeserialization() { public void testPrimitiveLongAutoboxedDeserialization() {
long expected = 1L; long expected = 1L;
long actual = gson.fromJson("1", long.class); long actual = gson.fromJson("1", long.class);
assertEquals(expected, actual); assertThat(actual).isEqualTo(expected);
actual = gson.fromJson("1", Long.class); actual = gson.fromJson("1", Long.class);
assertEquals(expected, actual); assertThat(actual).isEqualTo(expected);
} }
@Test @Test
public void testPrimitiveLongAutoboxedInASingleElementArraySerialization() { public void testPrimitiveLongAutoboxedInASingleElementArraySerialization() {
long[] target = {-23L}; long[] target = {-23L};
assertEquals("[-23]", gson.toJson(target)); assertThat(gson.toJson(target)).isEqualTo("[-23]");
assertEquals("[-23]", gson.toJson(target, long[].class)); assertThat(gson.toJson(target, long[].class)).isEqualTo("[-23]");
assertEquals("[-23]", gson.toJson(target, Long[].class)); assertThat(gson.toJson(target, Long[].class)).isEqualTo("[-23]");
} }
@Test @Test
public void testPrimitiveBooleanAutoboxedSerialization() { public void testPrimitiveBooleanAutoboxedSerialization() {
assertEquals("true", gson.toJson(true)); assertThat(gson.toJson(true)).isEqualTo("true");
assertEquals("false", gson.toJson(false)); assertThat(gson.toJson(false)).isEqualTo("false");
} }
@Test @Test
public void testBooleanDeserialization() { public void testBooleanDeserialization() {
boolean value = gson.fromJson("false", boolean.class); boolean value = gson.fromJson("false", boolean.class);
assertEquals(false, value); assertThat(value).isEqualTo(false);
value = gson.fromJson("true", boolean.class); value = gson.fromJson("true", boolean.class);
assertEquals(true, value); assertThat(value).isEqualTo(true);
} }
@Test @Test
public void testPrimitiveBooleanAutoboxedInASingleElementArraySerialization() { public void testPrimitiveBooleanAutoboxedInASingleElementArraySerialization() {
boolean target[] = {false}; boolean[] target = {false};
assertEquals("[false]", gson.toJson(target)); assertThat(gson.toJson(target)).isEqualTo("[false]");
assertEquals("[false]", gson.toJson(target, boolean[].class)); assertThat(gson.toJson(target, boolean[].class)).isEqualTo("[false]");
assertEquals("[false]", gson.toJson(target, Boolean[].class)); assertThat(gson.toJson(target, Boolean[].class)).isEqualTo("[false]");
} }
@Test @Test
public void testNumberSerialization() { public void testNumberSerialization() {
Number expected = 1L; Number expected = 1L;
String json = gson.toJson(expected); String json = gson.toJson(expected);
assertEquals(expected.toString(), json); assertThat(json).isEqualTo(expected.toString());
json = gson.toJson(expected, Number.class); json = gson.toJson(expected, Number.class);
assertEquals(expected.toString(), json); assertThat(json).isEqualTo(expected.toString());
} }
@Test @Test
@ -291,45 +288,45 @@ public class PrimitiveTest {
String json = "1"; String json = "1";
Number expected = Integer.valueOf(json); Number expected = Integer.valueOf(json);
Number actual = gson.fromJson(json, Number.class); Number actual = gson.fromJson(json, Number.class);
assertEquals(expected.intValue(), actual.intValue()); assertThat(actual.intValue()).isEqualTo(expected.intValue());
json = String.valueOf(Long.MAX_VALUE); json = String.valueOf(Long.MAX_VALUE);
expected = Long.valueOf(json); expected = Long.valueOf(json);
actual = gson.fromJson(json, Number.class); actual = gson.fromJson(json, Number.class);
assertEquals(expected.longValue(), actual.longValue()); assertThat(actual.longValue()).isEqualTo(expected.longValue());
json = "1.0"; json = "1.0";
actual = gson.fromJson(json, Number.class); actual = gson.fromJson(json, Number.class);
assertEquals(1L, actual.longValue()); assertThat(actual.longValue()).isEqualTo(1L);
} }
@Test @Test
public void testNumberAsStringDeserialization() { public void testNumberAsStringDeserialization() {
Number value = gson.fromJson("\"18\"", Number.class); Number value = gson.fromJson("\"18\"", Number.class);
assertEquals(18, value.intValue()); assertThat(value.intValue()).isEqualTo(18);
} }
@Test @Test
public void testPrimitiveDoubleAutoboxedSerialization() { public void testPrimitiveDoubleAutoboxedSerialization() {
assertEquals("-122.08234335", gson.toJson(-122.08234335D)); assertThat(gson.toJson(-122.08234335D)).isEqualTo("-122.08234335");
assertEquals("122.08112002", gson.toJson(122.08112002D)); assertThat(gson.toJson(122.08112002D)).isEqualTo("122.08112002");
} }
@Test @Test
public void testPrimitiveDoubleAutoboxedDeserialization() { public void testPrimitiveDoubleAutoboxedDeserialization() {
double actual = gson.fromJson("-122.08858585", double.class); double actual = gson.fromJson("-122.08858585", double.class);
assertEquals(-122.08858585D, actual, 0); assertThat(actual).isEqualTo(-122.08858585D);
actual = gson.fromJson("122.023900008000", Double.class); actual = gson.fromJson("122.023900008000", Double.class);
assertEquals(122.023900008D, actual, 0); assertThat(actual).isEqualTo(122.023900008D);
} }
@Test @Test
public void testPrimitiveDoubleAutoboxedInASingleElementArraySerialization() { public void testPrimitiveDoubleAutoboxedInASingleElementArraySerialization() {
double[] target = {-122.08D}; double[] target = {-122.08D};
assertEquals("[-122.08]", gson.toJson(target)); assertThat(gson.toJson(target)).isEqualTo("[-122.08]");
assertEquals("[-122.08]", gson.toJson(target, double[].class)); assertThat(gson.toJson(target, double[].class)).isEqualTo("[-122.08]");
assertEquals("[-122.08]", gson.toJson(target, Double[].class)); assertThat(gson.toJson(target, Double[].class)).isEqualTo("[-122.08]");
} }
@Test @Test
@ -337,10 +334,10 @@ public class PrimitiveTest {
String doubleValue = "1.0043E+5"; String doubleValue = "1.0043E+5";
Double expected = Double.valueOf(doubleValue); Double expected = Double.valueOf(doubleValue);
Double actual = gson.fromJson(doubleValue, Double.class); Double actual = gson.fromJson(doubleValue, Double.class);
assertEquals(expected, actual); assertThat(actual).isEqualTo(expected);
double actual1 = gson.fromJson(doubleValue, double.class); double actual1 = gson.fromJson(doubleValue, double.class);
assertEquals(expected, actual1, 0); assertThat(actual1).isEqualTo(expected);
} }
@Test @Test
@ -348,10 +345,10 @@ public class PrimitiveTest {
String doubleValue = "1E+5"; String doubleValue = "1E+5";
Double expected = Double.valueOf(doubleValue); Double expected = Double.valueOf(doubleValue);
Double actual = gson.fromJson(doubleValue, Double.class); Double actual = gson.fromJson(doubleValue, Double.class);
assertEquals(expected, actual); assertThat(actual).isEqualTo(expected);
double actual1 = gson.fromJson(doubleValue, double.class); double actual1 = gson.fromJson(doubleValue, double.class);
assertEquals(expected, actual1, 0); assertThat(actual1).isEqualTo(expected);
} }
@Test @Test
@ -359,13 +356,14 @@ public class PrimitiveTest {
String json = "[0.0, 0.004761904761904762, 3.4013606962703525E-4, 7.936508173034305E-4," String json = "[0.0, 0.004761904761904762, 3.4013606962703525E-4, 7.936508173034305E-4,"
+ "0.0011904761904761906, 0.0]"; + "0.0011904761904761906, 0.0]";
double[] values = gson.fromJson(json, double[].class); double[] values = gson.fromJson(json, double[].class);
assertEquals(6, values.length, 0);
assertEquals(0.0, values[0], 0); assertThat(values).hasLength(6);
assertEquals(0.004761904761904762, values[1], 0); assertThat(values[0]).isEqualTo(0.0);
assertEquals(3.4013606962703525E-4, values[2], 0); assertThat(values[1]).isEqualTo(0.004761904761904762);
assertEquals(7.936508173034305E-4, values[3], 0); assertThat(values[2]).isEqualTo(3.4013606962703525E-4);
assertEquals(0.0011904761904761906, values[4], 0); assertThat(values[3]).isEqualTo(7.936508173034305E-4);
assertEquals(0.0, values[5], 0); assertThat(values[4]).isEqualTo(0.0011904761904761906);
assertThat(values[5]).isEqualTo(0.0);
} }
@Test @Test
@ -373,24 +371,24 @@ public class PrimitiveTest {
String doubleValue = "1.234567899E8"; String doubleValue = "1.234567899E8";
Double expected = Double.valueOf(doubleValue); Double expected = Double.valueOf(doubleValue);
Double actual = gson.fromJson(doubleValue, Double.class); Double actual = gson.fromJson(doubleValue, Double.class);
assertEquals(expected, actual); assertThat(actual).isEqualTo(expected);
double actual1 = gson.fromJson(doubleValue, double.class); double actual1 = gson.fromJson(doubleValue, double.class);
assertEquals(expected, actual1, 0); assertThat(actual1).isEqualTo(expected);
} }
@Test @Test
public void testBigDecimalSerialization() { public void testBigDecimalSerialization() {
BigDecimal target = new BigDecimal("-122.0e-21"); BigDecimal target = new BigDecimal("-122.0e-21");
String json = gson.toJson(target); String json = gson.toJson(target);
assertEquals(target, new BigDecimal(json)); assertThat(new BigDecimal(json)).isEqualTo(target);
} }
@Test @Test
public void testBigDecimalDeserialization() { public void testBigDecimalDeserialization() {
BigDecimal target = new BigDecimal("-122.0e-21"); BigDecimal target = new BigDecimal("-122.0e-21");
String json = "-122.0e-21"; String json = "-122.0e-21";
assertEquals(target, gson.fromJson(json, BigDecimal.class)); assertThat(gson.fromJson(json, BigDecimal.class)).isEqualTo(target);
} }
@Test @Test
@ -398,25 +396,25 @@ public class PrimitiveTest {
BigDecimal[] target = {new BigDecimal("-122.08e-21")}; BigDecimal[] target = {new BigDecimal("-122.08e-21")};
String json = gson.toJson(target); String json = gson.toJson(target);
String actual = extractElementFromArray(json); String actual = extractElementFromArray(json);
assertEquals(target[0], new BigDecimal(actual)); assertThat(new BigDecimal(actual)).isEqualTo(target[0]);
json = gson.toJson(target, BigDecimal[].class); json = gson.toJson(target, BigDecimal[].class);
actual = extractElementFromArray(json); actual = extractElementFromArray(json);
assertEquals(target[0], new BigDecimal(actual)); assertThat(new BigDecimal(actual)).isEqualTo(target[0]);
} }
@Test @Test
public void testSmallValueForBigDecimalSerialization() { public void testSmallValueForBigDecimalSerialization() {
BigDecimal target = new BigDecimal("1.55"); BigDecimal target = new BigDecimal("1.55");
String actual = gson.toJson(target); String actual = gson.toJson(target);
assertEquals(target.toString(), actual); assertThat(actual).isEqualTo(target.toString());
} }
@Test @Test
public void testSmallValueForBigDecimalDeserialization() { public void testSmallValueForBigDecimalDeserialization() {
BigDecimal expected = new BigDecimal("1.55"); BigDecimal expected = new BigDecimal("1.55");
BigDecimal actual = gson.fromJson("1.55", BigDecimal.class); BigDecimal actual = gson.fromJson("1.55", BigDecimal.class);
assertEquals(expected, actual); assertThat(actual).isEqualTo(expected);
} }
@Test @Test
@ -425,7 +423,7 @@ public class PrimitiveTest {
BigDecimal obj = new BigDecimal(expectedValue); BigDecimal obj = new BigDecimal(expectedValue);
String actualValue = gson.toJson(obj); String actualValue = gson.toJson(obj);
assertEquals(expectedValue, actualValue); assertThat(actualValue).isEqualTo(expectedValue);
} }
@Test @Test
@ -434,7 +432,7 @@ public class PrimitiveTest {
BigDecimal expected = new BigDecimal(json); BigDecimal expected = new BigDecimal(json);
BigDecimal actual = gson.fromJson(json, BigDecimal.class); BigDecimal actual = gson.fromJson(json, BigDecimal.class);
assertEquals(expected, actual); assertThat(actual).isEqualTo(expected);
} }
@Test @Test
@ -442,7 +440,7 @@ public class PrimitiveTest {
String doubleValue = "0.05E+5"; String doubleValue = "0.05E+5";
BigDecimal expected = new BigDecimal(doubleValue); BigDecimal expected = new BigDecimal(doubleValue);
BigDecimal actual = gson.fromJson(doubleValue, BigDecimal.class); BigDecimal actual = gson.fromJson(doubleValue, BigDecimal.class);
assertEquals(expected, actual); assertThat(actual).isEqualTo(expected);
} }
@Test @Test
@ -450,20 +448,20 @@ public class PrimitiveTest {
String doubleValue = "5E+5"; String doubleValue = "5E+5";
BigDecimal expected = new BigDecimal(doubleValue); BigDecimal expected = new BigDecimal(doubleValue);
BigDecimal actual = gson.fromJson(doubleValue, BigDecimal.class); BigDecimal actual = gson.fromJson(doubleValue, BigDecimal.class);
assertEquals(expected, actual); assertThat(actual).isEqualTo(expected);
} }
@Test @Test
public void testBigIntegerSerialization() { public void testBigIntegerSerialization() {
BigInteger target = new BigInteger("12121211243123245845384534687435634558945453489543985435"); BigInteger target = new BigInteger("12121211243123245845384534687435634558945453489543985435");
assertEquals(target.toString(), gson.toJson(target)); assertThat(gson.toJson(target)).isEqualTo(target.toString());
} }
@Test @Test
public void testBigIntegerDeserialization() { public void testBigIntegerDeserialization() {
String json = "12121211243123245845384534687435634558945453489543985435"; String json = "12121211243123245845384534687435634558945453489543985435";
BigInteger target = new BigInteger(json); BigInteger target = new BigInteger(json);
assertEquals(target, gson.fromJson(json, BigInteger.class)); assertThat(gson.fromJson(json, BigInteger.class)).isEqualTo(target);
} }
@Test @Test
@ -471,25 +469,25 @@ public class PrimitiveTest {
BigInteger[] target = {new BigInteger("1212121243434324323254365345367456456456465464564564")}; BigInteger[] target = {new BigInteger("1212121243434324323254365345367456456456465464564564")};
String json = gson.toJson(target); String json = gson.toJson(target);
String actual = extractElementFromArray(json); String actual = extractElementFromArray(json);
assertEquals(target[0], new BigInteger(actual)); assertThat(new BigInteger(actual)).isEqualTo(target[0]);
json = gson.toJson(target, BigInteger[].class); json = gson.toJson(target, BigInteger[].class);
actual = extractElementFromArray(json); actual = extractElementFromArray(json);
assertEquals(target[0], new BigInteger(actual)); assertThat(new BigInteger(actual)).isEqualTo(target[0]);
} }
@Test @Test
public void testSmallValueForBigIntegerSerialization() { public void testSmallValueForBigIntegerSerialization() {
BigInteger target = new BigInteger("15"); BigInteger target = new BigInteger("15");
String actual = gson.toJson(target); String actual = gson.toJson(target);
assertEquals(target.toString(), actual); assertThat(actual).isEqualTo(target.toString());
} }
@Test @Test
public void testSmallValueForBigIntegerDeserialization() { public void testSmallValueForBigIntegerDeserialization() {
BigInteger expected = new BigInteger("15"); BigInteger expected = new BigInteger("15");
BigInteger actual = gson.fromJson("15", BigInteger.class); BigInteger actual = gson.fromJson("15", BigInteger.class);
assertEquals(expected, actual); assertThat(actual).isEqualTo(expected);
} }
@Test @Test
@ -504,14 +502,14 @@ public class PrimitiveTest {
public void testLazilyParsedNumberSerialization() { public void testLazilyParsedNumberSerialization() {
LazilyParsedNumber target = new LazilyParsedNumber("1.5"); LazilyParsedNumber target = new LazilyParsedNumber("1.5");
String actual = gson.toJson(target); String actual = gson.toJson(target);
assertEquals("1.5", actual); assertThat(actual).isEqualTo("1.5");
} }
@Test @Test
public void testLazilyParsedNumberDeserialization() { public void testLazilyParsedNumberDeserialization() {
LazilyParsedNumber expected = new LazilyParsedNumber("1.5"); LazilyParsedNumber expected = new LazilyParsedNumber("1.5");
LazilyParsedNumber actual = gson.fromJson("1.5", LazilyParsedNumber.class); LazilyParsedNumber actual = gson.fromJson("1.5", LazilyParsedNumber.class);
assertEquals(expected, actual); assertThat(actual).isEqualTo(expected);
} }
@Test @Test
@ -522,7 +520,7 @@ public class PrimitiveTest {
Serializable serializableString = expected; Serializable serializableString = expected;
String actualJson = gson.toJson(serializableString, Serializable.class); String actualJson = gson.toJson(serializableString, Serializable.class);
assertFalse(expectedJson.equals(actualJson)); assertThat(actualJson).isNotEqualTo(expectedJson);
} }
private String extractElementFromArray(String json) { private String extractElementFromArray(String json) {
@ -548,14 +546,14 @@ public class PrimitiveTest {
public void testDoubleNaNSerialization() { public void testDoubleNaNSerialization() {
Gson gson = new GsonBuilder().setLenient().serializeSpecialFloatingPointValues().create(); Gson gson = new GsonBuilder().setLenient().serializeSpecialFloatingPointValues().create();
double nan = Double.NaN; double nan = Double.NaN;
assertEquals("NaN", gson.toJson(nan)); assertThat(gson.toJson(nan)).isEqualTo("NaN");
assertEquals("NaN", gson.toJson(Double.NaN)); assertThat(gson.toJson(Double.NaN)).isEqualTo("NaN");
} }
@Test @Test
public void testDoubleNaNDeserialization() { public void testDoubleNaNDeserialization() {
assertTrue(Double.isNaN(gson.fromJson("NaN", Double.class))); assertThat(Double.isNaN(gson.fromJson("NaN", Double.class))).isTrue();
assertTrue(Double.isNaN(gson.fromJson("NaN", double.class))); assertThat(Double.isNaN(gson.fromJson("NaN", double.class))).isTrue();
} }
@Test @Test
@ -577,14 +575,14 @@ public class PrimitiveTest {
public void testFloatNaNSerialization() { public void testFloatNaNSerialization() {
Gson gson = new GsonBuilder().setLenient().serializeSpecialFloatingPointValues().create(); Gson gson = new GsonBuilder().setLenient().serializeSpecialFloatingPointValues().create();
float nan = Float.NaN; float nan = Float.NaN;
assertEquals("NaN", gson.toJson(nan)); assertThat(gson.toJson(nan)).isEqualTo("NaN");
assertEquals("NaN", gson.toJson(Float.NaN)); assertThat(gson.toJson(Float.NaN)).isEqualTo("NaN");
} }
@Test @Test
public void testFloatNaNDeserialization() { public void testFloatNaNDeserialization() {
assertTrue(Float.isNaN(gson.fromJson("NaN", Float.class))); assertThat(Float.isNaN(gson.fromJson("NaN", Float.class))).isTrue();
assertTrue(Float.isNaN(gson.fromJson("NaN", float.class))); assertThat(Float.isNaN(gson.fromJson("NaN", float.class))).isTrue();
} }
@Test @Test
@ -615,14 +613,14 @@ public class PrimitiveTest {
public void testDoubleInfinitySerialization() { public void testDoubleInfinitySerialization() {
Gson gson = new GsonBuilder().setLenient().serializeSpecialFloatingPointValues().create(); Gson gson = new GsonBuilder().setLenient().serializeSpecialFloatingPointValues().create();
double infinity = Double.POSITIVE_INFINITY; double infinity = Double.POSITIVE_INFINITY;
assertEquals("Infinity", gson.toJson(infinity)); assertThat(gson.toJson(infinity)).isEqualTo("Infinity");
assertEquals("Infinity", gson.toJson(Double.POSITIVE_INFINITY)); assertThat(gson.toJson(Double.POSITIVE_INFINITY)).isEqualTo("Infinity");
} }
@Test @Test
public void testDoubleInfinityDeserialization() { public void testDoubleInfinityDeserialization() {
assertTrue(Double.isInfinite(gson.fromJson("Infinity", Double.class))); assertThat(Double.isInfinite(gson.fromJson("Infinity", Double.class))).isTrue();
assertTrue(Double.isInfinite(gson.fromJson("Infinity", double.class))); assertThat(Double.isInfinite(gson.fromJson("Infinity", double.class))).isTrue();
} }
@Test @Test
@ -644,14 +642,14 @@ public class PrimitiveTest {
public void testFloatInfinitySerialization() { public void testFloatInfinitySerialization() {
Gson gson = new GsonBuilder().setLenient().serializeSpecialFloatingPointValues().create(); Gson gson = new GsonBuilder().setLenient().serializeSpecialFloatingPointValues().create();
float infinity = Float.POSITIVE_INFINITY; float infinity = Float.POSITIVE_INFINITY;
assertEquals("Infinity", gson.toJson(infinity)); assertThat(gson.toJson(infinity)).isEqualTo("Infinity");
assertEquals("Infinity", gson.toJson(Float.POSITIVE_INFINITY)); assertThat(gson.toJson(Float.POSITIVE_INFINITY)).isEqualTo("Infinity");
} }
@Test @Test
public void testFloatInfinityDeserialization() { public void testFloatInfinityDeserialization() {
assertTrue(Float.isInfinite(gson.fromJson("Infinity", Float.class))); assertThat(Float.isInfinite(gson.fromJson("Infinity", Float.class))).isTrue();
assertTrue(Float.isInfinite(gson.fromJson("Infinity", float.class))); assertThat(Float.isInfinite(gson.fromJson("Infinity", float.class))).isTrue();
} }
@Test @Test
@ -682,14 +680,14 @@ public class PrimitiveTest {
public void testNegativeInfinitySerialization() { public void testNegativeInfinitySerialization() {
Gson gson = new GsonBuilder().setLenient().serializeSpecialFloatingPointValues().create(); Gson gson = new GsonBuilder().setLenient().serializeSpecialFloatingPointValues().create();
double negativeInfinity = Double.NEGATIVE_INFINITY; double negativeInfinity = Double.NEGATIVE_INFINITY;
assertEquals("-Infinity", gson.toJson(negativeInfinity)); assertThat(gson.toJson(negativeInfinity)).isEqualTo("-Infinity");
assertEquals("-Infinity", gson.toJson(Double.NEGATIVE_INFINITY)); assertThat(gson.toJson(Double.NEGATIVE_INFINITY)).isEqualTo("-Infinity");
} }
@Test @Test
public void testNegativeInfinityDeserialization() { public void testNegativeInfinityDeserialization() {
assertTrue(Double.isInfinite(gson.fromJson("-Infinity", double.class))); assertThat(Double.isInfinite(gson.fromJson("-Infinity", double.class))).isTrue();
assertTrue(Double.isInfinite(gson.fromJson("-Infinity", Double.class))); assertThat(Double.isInfinite(gson.fromJson("-Infinity", Double.class))).isTrue();
} }
@Test @Test
@ -711,14 +709,14 @@ public class PrimitiveTest {
public void testNegativeInfinityFloatSerialization() { public void testNegativeInfinityFloatSerialization() {
Gson gson = new GsonBuilder().setLenient().serializeSpecialFloatingPointValues().create(); Gson gson = new GsonBuilder().setLenient().serializeSpecialFloatingPointValues().create();
float negativeInfinity = Float.NEGATIVE_INFINITY; float negativeInfinity = Float.NEGATIVE_INFINITY;
assertEquals("-Infinity", gson.toJson(negativeInfinity)); assertThat(gson.toJson(negativeInfinity)).isEqualTo("-Infinity");
assertEquals("-Infinity", gson.toJson(Float.NEGATIVE_INFINITY)); assertThat(gson.toJson(Float.NEGATIVE_INFINITY)).isEqualTo("-Infinity");
} }
@Test @Test
public void testNegativeInfinityFloatDeserialization() { public void testNegativeInfinityFloatDeserialization() {
assertTrue(Float.isInfinite(gson.fromJson("-Infinity", float.class))); assertThat(Float.isInfinite(gson.fromJson("-Infinity", float.class))).isTrue();
assertTrue(Float.isInfinite(gson.fromJson("-Infinity", Float.class))); assertThat(Float.isInfinite(gson.fromJson("-Infinity", Float.class))).isTrue();
} }
@Test @Test
@ -731,39 +729,39 @@ public class PrimitiveTest {
} }
@Test @Test
public void testLongAsStringSerialization() throws Exception { public void testLongAsStringSerialization() {
gson = new GsonBuilder().setLongSerializationPolicy(LongSerializationPolicy.STRING).create(); gson = new GsonBuilder().setLongSerializationPolicy(LongSerializationPolicy.STRING).create();
String result = gson.toJson(15L); String result = gson.toJson(15L);
assertEquals("\"15\"", result); assertThat(result).isEqualTo("\"15\"");
// Test with an integer and ensure its still a number // Test with an integer and ensure its still a number
result = gson.toJson(2); result = gson.toJson(2);
assertEquals("2", result); assertThat(result).isEqualTo("2");
} }
@Test @Test
public void testLongAsStringDeserialization() throws Exception { public void testLongAsStringDeserialization() {
long value = gson.fromJson("\"15\"", long.class); long value = gson.fromJson("\"15\"", long.class);
assertEquals(15, value); assertThat(value).isEqualTo(15);
gson = new GsonBuilder().setLongSerializationPolicy(LongSerializationPolicy.STRING).create(); gson = new GsonBuilder().setLongSerializationPolicy(LongSerializationPolicy.STRING).create();
value = gson.fromJson("\"25\"", long.class); value = gson.fromJson("\"25\"", long.class);
assertEquals(25, value); assertThat(value).isEqualTo(25);
} }
@Test @Test
public void testQuotedStringSerializationAndDeserialization() throws Exception { public void testQuotedStringSerializationAndDeserialization() {
String value = "String Blah Blah Blah...1, 2, 3"; String value = "String Blah Blah Blah...1, 2, 3";
String serializedForm = gson.toJson(value); String serializedForm = gson.toJson(value);
assertEquals("\"" + value + "\"", serializedForm); assertThat(serializedForm).isEqualTo("\"" + value + "\"");
String actual = gson.fromJson(serializedForm, String.class); String actual = gson.fromJson(serializedForm, String.class);
assertEquals(value, actual); assertThat(actual).isEqualTo(value);
} }
@Test @Test
public void testUnquotedStringDeserializationFails() throws Exception { public void testUnquotedStringDeserializationFails() {
assertEquals("UnquotedSingleWord", gson.fromJson("UnquotedSingleWord", String.class)); assertThat(gson.fromJson("UnquotedSingleWord", String.class)).isEqualTo("UnquotedSingleWord");
String value = "String Blah Blah Blah...1, 2, 3"; String value = "String Blah Blah Blah...1, 2, 3";
try { try {
@ -773,21 +771,21 @@ public class PrimitiveTest {
} }
@Test @Test
public void testHtmlCharacterSerialization() throws Exception { public void testHtmlCharacterSerialization() {
String target = "<script>var a = 12;</script>"; String target = "<script>var a = 12;</script>";
String result = gson.toJson(target); String result = gson.toJson(target);
assertFalse(result.equals('"' + target + '"')); assertThat(result).isNotEqualTo('"' + target + '"');
gson = new GsonBuilder().disableHtmlEscaping().create(); gson = new GsonBuilder().disableHtmlEscaping().create();
result = gson.toJson(target); result = gson.toJson(target);
assertTrue(result.equals('"' + target + '"')); assertThat(result).isEqualTo('"' + target + '"');
} }
@Test @Test
public void testDeserializePrimitiveWrapperAsObjectField() { public void testDeserializePrimitiveWrapperAsObjectField() {
String json = "{i:10}"; String json = "{i:10}";
ClassWithIntegerField target = gson.fromJson(json, ClassWithIntegerField.class); ClassWithIntegerField target = gson.fromJson(json, ClassWithIntegerField.class);
assertEquals(10, target.i.intValue()); assertThat(target.i).isEqualTo(10);
} }
private static class ClassWithIntegerField { private static class ClassWithIntegerField {
@ -796,9 +794,9 @@ public class PrimitiveTest {
@Test @Test
public void testPrimitiveClassLiteral() { public void testPrimitiveClassLiteral() {
assertEquals(1, gson.fromJson("1", int.class).intValue()); assertThat(gson.fromJson("1", int.class)).isEqualTo(1);
assertEquals(1, gson.fromJson(new StringReader("1"), int.class).intValue()); assertThat(gson.fromJson(new StringReader("1"), int.class)).isEqualTo(1);
assertEquals(1, gson.fromJson(new JsonPrimitive(1), int.class).intValue()); assertThat(gson.fromJson(new JsonPrimitive(1), int.class)).isEqualTo(1);
} }
@Test @Test
@ -963,7 +961,7 @@ public class PrimitiveTest {
@Test @Test
public void testDeserializingDecimalPointValueZeroSucceeds() { public void testDeserializingDecimalPointValueZeroSucceeds() {
assertEquals(1, (int) gson.fromJson("1.0", Integer.class)); assertThat(gson.fromJson("1.0", Integer.class)).isEqualTo(1);
} }
@Test @Test
@ -1019,28 +1017,28 @@ public class PrimitiveTest {
@Test @Test
public void testValueVeryCloseToZeroIsZero() { public void testValueVeryCloseToZeroIsZero() {
assertEquals(0, (byte) gson.fromJson("-122.08e-2132", byte.class)); assertThat(gson.fromJson("-122.08e-2132", byte.class)).isEqualTo(0);
assertEquals(0, (short) gson.fromJson("-122.08e-2132", short.class)); assertThat(gson.fromJson("-122.08e-2132", short.class)).isEqualTo(0);
assertEquals(0, (int) gson.fromJson("-122.08e-2132", int.class)); assertThat(gson.fromJson("-122.08e-2132", int.class)).isEqualTo(0);
assertEquals(0, (long) gson.fromJson("-122.08e-2132", long.class)); assertThat(gson.fromJson("-122.08e-2132", long.class)).isEqualTo(0);
assertEquals(-0.0f, gson.fromJson("-122.08e-2132", float.class), 0); assertThat(gson.fromJson("-122.08e-2132", float.class)).isEqualTo(-0.0f);
assertEquals(-0.0, gson.fromJson("-122.08e-2132", double.class), 0); assertThat(gson.fromJson("-122.08e-2132", double.class)).isEqualTo(-0.0);
assertEquals(0.0f, gson.fromJson("122.08e-2132", float.class), 0); assertThat(gson.fromJson("122.08e-2132", float.class)).isEqualTo(0.0f);
assertEquals(0.0, gson.fromJson("122.08e-2132", double.class), 0); assertThat(gson.fromJson("122.08e-2132", double.class)).isEqualTo(0.0);
} }
@Test @Test
public void testDeserializingBigDecimalAsFloat() { public void testDeserializingBigDecimalAsFloat() {
String json = "-122.08e-2132332"; String json = "-122.08e-2132332";
float actual = gson.fromJson(json, float.class); float actual = gson.fromJson(json, float.class);
assertEquals(-0.0f, actual, 0); assertThat(actual).isEqualTo(-0.0f);
} }
@Test @Test
public void testDeserializingBigDecimalAsDouble() { public void testDeserializingBigDecimalAsDouble() {
String json = "-122.08e-2132332"; String json = "-122.08e-2132332";
double actual = gson.fromJson(json, double.class); double actual = gson.fromJson(json, double.class);
assertEquals(-0.0d, actual, 0); assertThat(actual).isEqualTo(-0.0d);
} }
@Test @Test
@ -1056,13 +1054,12 @@ public class PrimitiveTest {
public void testDeserializingBigIntegerAsBigDecimal() { public void testDeserializingBigIntegerAsBigDecimal() {
BigDecimal actual = BigDecimal actual =
gson.fromJson("12121211243123245845384534687435634558945453489543985435", BigDecimal.class); gson.fromJson("12121211243123245845384534687435634558945453489543985435", BigDecimal.class);
assertEquals("12121211243123245845384534687435634558945453489543985435", actual.toPlainString()); assertThat(actual.toPlainString()).isEqualTo("12121211243123245845384534687435634558945453489543985435");
} }
@Test @Test
public void testStringsAsBooleans() { public void testStringsAsBooleans() {
String json = "['true', 'false', 'TRUE', 'yes', '1']"; String json = "['true', 'false', 'TRUE', 'yes', '1']";
assertEquals(Arrays.asList(true, false, true, false, false), assertThat( gson.<List<Boolean>>fromJson(json, new TypeToken<List<Boolean>>() {}.getType())).isEqualTo(Arrays.asList(true, false, true, false, false));
gson.<List<Boolean>>fromJson(json, new TypeToken<List<Boolean>>() {}.getType()));
} }
} }

View File

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

View File

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

View File

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

View File

@ -1,6 +1,22 @@
/*
* Copyright (C) 2022 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.gson.functional; package com.google.gson.functional;
import static org.junit.Assert.assertEquals; import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import static org.junit.Assume.assumeNotNull; import static org.junit.Assume.assumeNotNull;
@ -52,12 +68,10 @@ public class ReflectionAccessFilterTest {
fail("Expected exception; test needs to be run with Java >= 9"); fail("Expected exception; test needs to be run with Java >= 9");
} catch (JsonIOException expected) { } catch (JsonIOException expected) {
// Note: This test is rather brittle and depends on the JDK implementation // Note: This test is rather brittle and depends on the JDK implementation
assertEquals( assertThat(expected).hasMessageThat()
"Field 'java.io.File#path' is not accessible and ReflectionAccessFilter does not permit" .isEqualTo("Field 'java.io.File#path' is not accessible and ReflectionAccessFilter does not permit"
+ " making it accessible. Register a TypeAdapter for the declaring type, adjust the access" + " making it accessible. Register a TypeAdapter for the declaring type, adjust the access"
+ " filter or increase the visibility of the element and its declaring type.", + " filter or increase the visibility of the element and its declaring type.");
expected.getMessage()
);
} }
@ -72,7 +86,7 @@ public class ReflectionAccessFilterTest {
Constructor<?> pointConstructor = pointClass.getConstructor(int.class, int.class); Constructor<?> pointConstructor = pointClass.getConstructor(int.class, int.class);
Object point = pointConstructor.newInstance(1, 2); Object point = pointConstructor.newInstance(1, 2);
String json = gson.toJson(point); String json = gson.toJson(point);
assertEquals("{\"x\":1,\"y\":2}", json); assertThat(json).isEqualTo("{\"x\":1,\"y\":2}");
} }
@Test @Test
@ -85,12 +99,10 @@ public class ReflectionAccessFilterTest {
gson.toJson(new ClassExtendingJdkClass()); gson.toJson(new ClassExtendingJdkClass());
fail("Expected exception; test needs to be run with Java >= 9"); fail("Expected exception; test needs to be run with Java >= 9");
} catch (JsonIOException expected) { } catch (JsonIOException expected) {
assertEquals( assertThat(expected).hasMessageThat()
"Field 'java.io.Reader#lock' is not accessible and ReflectionAccessFilter does not permit" .isEqualTo("Field 'java.io.Reader#lock' is not accessible and ReflectionAccessFilter does not permit"
+ " making it accessible. Register a TypeAdapter for the declaring type, adjust the access" + " making it accessible. Register a TypeAdapter for the declaring type, adjust the access"
+ " filter or increase the visibility of the element and its declaring type.", + " filter or increase the visibility of the element and its declaring type.");
expected.getMessage()
);
} }
} }
@ -105,11 +117,9 @@ public class ReflectionAccessFilterTest {
gson.toJson(Thread.currentThread()); gson.toJson(Thread.currentThread());
fail(); fail();
} catch (JsonIOException expected) { } catch (JsonIOException expected) {
assertEquals( assertThat(expected).hasMessageThat()
"ReflectionAccessFilter does not permit using reflection for class java.lang.Thread." .isEqualTo("ReflectionAccessFilter does not permit using reflection for class java.lang.Thread."
+ " Register a TypeAdapter for this type or adjust the access filter.", + " Register a TypeAdapter for this type or adjust the access filter.");
expected.getMessage()
);
} }
} }
@ -123,12 +133,10 @@ public class ReflectionAccessFilterTest {
gson.toJson(new ClassExtendingJdkClass()); gson.toJson(new ClassExtendingJdkClass());
fail(); fail();
} catch (JsonIOException expected) { } catch (JsonIOException expected) {
assertEquals( assertThat(expected).hasMessageThat()
"ReflectionAccessFilter does not permit using reflection for class java.io.Reader" .isEqualTo("ReflectionAccessFilter does not permit using reflection for class java.io.Reader"
+ " (supertype of class com.google.gson.functional.ReflectionAccessFilterTest$ClassExtendingJdkClass)." + " (supertype of class com.google.gson.functional.ReflectionAccessFilterTest$ClassExtendingJdkClass)."
+ " Register a TypeAdapter for this type or adjust the access filter.", + " Register a TypeAdapter for this type or adjust the access filter.");
expected.getMessage()
);
} }
} }
@ -153,13 +161,11 @@ public class ReflectionAccessFilterTest {
gson.toJson(new ClassWithStaticField()); gson.toJson(new ClassWithStaticField());
fail("Expected exception; test needs to be run with Java >= 9"); fail("Expected exception; test needs to be run with Java >= 9");
} catch (JsonIOException expected) { } catch (JsonIOException expected) {
assertEquals( assertThat(expected).hasMessageThat()
"Field 'com.google.gson.functional.ReflectionAccessFilterTest$ClassWithStaticField#i'" .isEqualTo("Field 'com.google.gson.functional.ReflectionAccessFilterTest$ClassWithStaticField#i'"
+ " is not accessible and ReflectionAccessFilter does not permit making it accessible." + " is not accessible and ReflectionAccessFilter does not permit making it accessible."
+ " Register a TypeAdapter for the declaring type, adjust the access filter or increase" + " Register a TypeAdapter for the declaring type, adjust the access filter or increase"
+ " the visibility of the element and its declaring type.", + " the visibility of the element and its declaring type.");
expected.getMessage()
);
} }
} }
@ -196,21 +202,18 @@ public class ReflectionAccessFilterTest {
gson.toJson(new SuperTestClass()); gson.toJson(new SuperTestClass());
fail(); fail();
} catch (JsonIOException expected) { } catch (JsonIOException expected) {
assertEquals( assertThat(expected).hasMessageThat().isEqualTo("ReflectionAccessFilter does not permit using reflection for class"
"ReflectionAccessFilter does not permit using reflection for class"
+ " com.google.gson.functional.ReflectionAccessFilterTest$SuperTestClass." + " com.google.gson.functional.ReflectionAccessFilterTest$SuperTestClass."
+ " Register a TypeAdapter for this type or adjust the access filter.", + " Register a TypeAdapter for this type or adjust the access filter.");
expected.getMessage()
);
} }
// But registration order is reversed, so filter for SubTestClass allows reflection // But registration order is reversed, so filter for SubTestClass allows reflection
String json = gson.toJson(new SubTestClass()); String json = gson.toJson(new SubTestClass());
assertEquals("{\"i\":1}", json); assertThat(json).isEqualTo("{\"i\":1}");
// And unrelated class should not be affected // And unrelated class should not be affected
json = gson.toJson(new OtherClass()); json = gson.toJson(new OtherClass());
assertEquals("{\"i\":2}", json); assertThat(json).isEqualTo("{\"i\":2}");
} }
private static class ClassWithPrivateField { private static class ClassWithPrivateField {
@ -235,13 +238,10 @@ public class ReflectionAccessFilterTest {
gson.toJson(new ExtendingClassWithPrivateField()); gson.toJson(new ExtendingClassWithPrivateField());
fail("Expected exception; test needs to be run with Java >= 9"); fail("Expected exception; test needs to be run with Java >= 9");
} catch (JsonIOException expected) { } catch (JsonIOException expected) {
assertEquals( assertThat(expected).hasMessageThat().isEqualTo("Field 'com.google.gson.functional.ReflectionAccessFilterTest$ClassWithPrivateField#i'"
"Field 'com.google.gson.functional.ReflectionAccessFilterTest$ClassWithPrivateField#i'"
+ " is not accessible and ReflectionAccessFilter does not permit making it accessible." + " is not accessible and ReflectionAccessFilter does not permit making it accessible."
+ " Register a TypeAdapter for the declaring type, adjust the access filter or increase" + " Register a TypeAdapter for the declaring type, adjust the access filter or increase"
+ " the visibility of the element and its declaring type.", + " the visibility of the element and its declaring type.");
expected.getMessage()
);
} }
gson = gson.newBuilder() gson = gson.newBuilder()
@ -255,7 +255,7 @@ public class ReflectionAccessFilterTest {
// Inherited (inaccessible) private field should have been made accessible // Inherited (inaccessible) private field should have been made accessible
String json = gson.toJson(new ExtendingClassWithPrivateField()); String json = gson.toJson(new ExtendingClassWithPrivateField());
assertEquals("{\"i\":1}", json); assertThat(json).isEqualTo("{\"i\":1}");
} }
private static class ClassWithPrivateNoArgsConstructor { private static class ClassWithPrivateNoArgsConstructor {
@ -277,12 +277,9 @@ public class ReflectionAccessFilterTest {
gson.fromJson("{}", ClassWithPrivateNoArgsConstructor.class); gson.fromJson("{}", ClassWithPrivateNoArgsConstructor.class);
fail("Expected exception; test needs to be run with Java >= 9"); fail("Expected exception; test needs to be run with Java >= 9");
} catch (JsonIOException expected) { } catch (JsonIOException expected) {
assertEquals( assertThat(expected).hasMessageThat().isEqualTo("Unable to invoke no-args constructor of class com.google.gson.functional.ReflectionAccessFilterTest$ClassWithPrivateNoArgsConstructor;"
"Unable to invoke no-args constructor of class com.google.gson.functional.ReflectionAccessFilterTest$ClassWithPrivateNoArgsConstructor;"
+ " constructor is not accessible and ReflectionAccessFilter does not permit making it accessible. Register an" + " constructor is not accessible and ReflectionAccessFilter does not permit making it accessible. Register an"
+ " InstanceCreator or a TypeAdapter for this type, change the visibility of the constructor or adjust the access filter.", + " InstanceCreator or a TypeAdapter for this type, change the visibility of the constructor or adjust the access filter.");
expected.getMessage()
);
} }
} }
@ -309,12 +306,9 @@ public class ReflectionAccessFilterTest {
gson.fromJson("{}", ClassWithoutNoArgsConstructor.class); gson.fromJson("{}", ClassWithoutNoArgsConstructor.class);
fail(); fail();
} catch (JsonIOException expected) { } catch (JsonIOException expected) {
assertEquals( assertThat(expected).hasMessageThat().isEqualTo("Unable to create instance of class com.google.gson.functional.ReflectionAccessFilterTest$ClassWithoutNoArgsConstructor;"
"Unable to create instance of class com.google.gson.functional.ReflectionAccessFilterTest$ClassWithoutNoArgsConstructor;"
+ " ReflectionAccessFilter does not permit using reflection or Unsafe. Register an InstanceCreator" + " ReflectionAccessFilter does not permit using reflection or Unsafe. Register an InstanceCreator"
+ " or a TypeAdapter for this type or adjust the access filter to allow using reflection.", + " or a TypeAdapter for this type or adjust the access filter to allow using reflection.");
expected.getMessage()
);
} }
// But should not fail when custom TypeAdapter is specified // But should not fail when custom TypeAdapter is specified
@ -324,13 +318,13 @@ public class ReflectionAccessFilterTest {
in.skipValue(); in.skipValue();
return new ClassWithoutNoArgsConstructor("TypeAdapter"); return new ClassWithoutNoArgsConstructor("TypeAdapter");
} }
@Override public void write(JsonWriter out, ClassWithoutNoArgsConstructor value) throws IOException { @Override public void write(JsonWriter out, ClassWithoutNoArgsConstructor value) {
throw new AssertionError("Not needed for test"); throw new AssertionError("Not needed for test");
} }
}) })
.create(); .create();
ClassWithoutNoArgsConstructor deserialized = gson.fromJson("{}", ClassWithoutNoArgsConstructor.class); ClassWithoutNoArgsConstructor deserialized = gson.fromJson("{}", ClassWithoutNoArgsConstructor.class);
assertEquals("TypeAdapter", deserialized.s); assertThat(deserialized.s).isEqualTo("TypeAdapter");
// But should not fail when custom InstanceCreator is specified // But should not fail when custom InstanceCreator is specified
gson = gsonBuilder gson = gsonBuilder
@ -341,7 +335,7 @@ public class ReflectionAccessFilterTest {
}) })
.create(); .create();
deserialized = gson.fromJson("{}", ClassWithoutNoArgsConstructor.class); deserialized = gson.fromJson("{}", ClassWithoutNoArgsConstructor.class);
assertEquals("InstanceCreator", deserialized.s); assertThat(deserialized.s).isEqualTo("InstanceCreator");
} }
/** /**
@ -364,18 +358,15 @@ public class ReflectionAccessFilterTest {
.create(); .create();
String json = gson.toJson(new OtherClass()); String json = gson.toJson(new OtherClass());
assertEquals("123", json); assertThat(json).isEqualTo("123");
// But deserialization should fail // But deserialization should fail
try { try {
gson.fromJson("{}", OtherClass.class); gson.fromJson("{}", OtherClass.class);
fail(); fail();
} catch (JsonIOException expected) { } catch (JsonIOException expected) {
assertEquals( assertThat(expected).hasMessageThat().isEqualTo("ReflectionAccessFilter does not permit using reflection for class com.google.gson.functional.ReflectionAccessFilterTest$OtherClass."
"ReflectionAccessFilter does not permit using reflection for class com.google.gson.functional.ReflectionAccessFilterTest$OtherClass." + " Register a TypeAdapter for this type or adjust the access filter.");
+ " Register a TypeAdapter for this type or adjust the access filter.",
expected.getMessage()
);
} }
} }
@ -393,7 +384,7 @@ public class ReflectionAccessFilterTest {
}) })
.create(); .create();
List<?> deserialized = gson.fromJson("[1.0]", List.class); List<?> deserialized = gson.fromJson("[1.0]", List.class);
assertEquals(1.0, deserialized.get(0)); assertThat(deserialized.get(0)).isEqualTo(1.0);
} }
/** /**
@ -410,7 +401,7 @@ public class ReflectionAccessFilterTest {
}) })
.create(); .create();
List<?> deserialized = gson.fromJson("[1.0]", LinkedList.class); List<?> deserialized = gson.fromJson("[1.0]", LinkedList.class);
assertEquals(1.0, deserialized.get(0)); assertThat(deserialized.get(0)).isEqualTo(1.0);
} }
/** /**
@ -431,11 +422,8 @@ public class ReflectionAccessFilterTest {
gson.fromJson("{}", Runnable.class); gson.fromJson("{}", Runnable.class);
fail(); fail();
} catch (JsonIOException expected) { } catch (JsonIOException expected) {
assertEquals( assertThat(expected).hasMessageThat().isEqualTo("Interfaces can't be instantiated! Register an InstanceCreator or a TypeAdapter for"
"Interfaces can't be instantiated! Register an InstanceCreator or a TypeAdapter for" + " this type. Interface name: java.lang.Runnable");
+ " this type. Interface name: java.lang.Runnable",
expected.getMessage()
);
} }
} }
} }

View File

@ -1,8 +1,22 @@
/*
* Copyright (C) 2021 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.gson.functional; package com.google.gson.functional;
import static org.junit.Assert.assertEquals; import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import com.google.gson.Gson; import com.google.gson.Gson;
@ -45,7 +59,7 @@ public class ReflectionAccessTest {
public void testSerializeInternalImplementationObject() { public void testSerializeInternalImplementationObject() {
Gson gson = new Gson(); Gson gson = new Gson();
String json = gson.toJson(Collections.emptyList()); String json = gson.toJson(Collections.emptyList());
assertEquals("[]", json); assertThat(json).isEqualTo("[]");
// But deserialization should fail // But deserialization should fail
Class<?> internalClass = Collections.emptyList().getClass(); Class<?> internalClass = Collections.emptyList().getClass();
@ -55,10 +69,8 @@ public class ReflectionAccessTest {
} catch (JsonSyntaxException e) { } catch (JsonSyntaxException e) {
fail("Unexpected exception; test has to be run with `--illegal-access=deny`"); fail("Unexpected exception; test has to be run with `--illegal-access=deny`");
} catch (JsonIOException expected) { } catch (JsonIOException expected) {
assertTrue(expected.getMessage().startsWith( assertThat(expected).hasMessageThat().startsWith("Failed making constructor 'java.util.Collections$EmptyList()' accessible;"
"Failed making constructor 'java.util.Collections$EmptyList()' accessible;" + " either increase its visibility or write a custom InstanceCreator or TypeAdapter for its declaring type: ");
+ " either increase its visibility or write a custom InstanceCreator or TypeAdapter for its declaring type: "
));
} }
} }
} }

View File

@ -1,8 +1,22 @@
/*
* Copyright (C) 2018 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.gson.functional; package com.google.gson.functional;
import static org.junit.Assert.assertEquals; import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;
@ -31,14 +45,14 @@ public class ReusedTypeVariablesFullyResolveTest {
public void testGenericsPreservation() { public void testGenericsPreservation() {
TestEnumSetCollection withSet = gson.fromJson("{\"collection\":[\"ONE\",\"THREE\"]}", TestEnumSetCollection.class); TestEnumSetCollection withSet = gson.fromJson("{\"collection\":[\"ONE\",\"THREE\"]}", TestEnumSetCollection.class);
Iterator<TestEnum> iterator = withSet.collection.iterator(); Iterator<TestEnum> iterator = withSet.collection.iterator();
assertNotNull(withSet); assertThat(withSet).isNotNull();
assertNotNull(withSet.collection); assertThat(withSet.collection).isNotNull();
assertEquals(2, withSet.collection.size()); assertThat(withSet.collection).hasSize(2);
TestEnum first = iterator.next(); TestEnum first = iterator.next();
TestEnum second = iterator.next(); TestEnum second = iterator.next();
assertTrue(first instanceof TestEnum); assertThat(first).isInstanceOf(TestEnum.class);
assertTrue(second instanceof TestEnum); assertThat(second).isInstanceOf(TestEnum.class);
} }
enum TestEnum { ONE, TWO, THREE } enum TestEnum { ONE, TWO, THREE }

View File

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

View File

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

View File

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

View File

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

View File

@ -1,6 +1,22 @@
/*
* Copyright (C) 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.gson.functional; package com.google.gson.functional;
import static org.junit.Assert.assertEquals; import static com.google.common.truth.Truth.assertThat;
import com.google.gson.Gson; import com.google.gson.Gson;
import org.junit.Before; import org.junit.Before;
@ -21,94 +37,94 @@ public class StringTest {
} }
@Test @Test
public void testStringValueSerialization() throws Exception { public void testStringValueSerialization() {
String value = "someRandomStringValue"; String value = "someRandomStringValue";
assertEquals('"' + value + '"', gson.toJson(value)); assertThat(gson.toJson(value)).isEqualTo('"' + value + '"');
} }
@Test @Test
public void testStringValueDeserialization() throws Exception { public void testStringValueDeserialization() {
String value = "someRandomStringValue"; String value = "someRandomStringValue";
String actual = gson.fromJson("\"" + value + "\"", String.class); String actual = gson.fromJson("\"" + value + "\"", String.class);
assertEquals(value, actual); assertThat(actual).isEqualTo(value);
} }
@Test @Test
public void testSingleQuoteInStringSerialization() throws Exception { public void testSingleQuoteInStringSerialization() {
String valueWithQuotes = "beforeQuote'afterQuote"; String valueWithQuotes = "beforeQuote'afterQuote";
String jsonRepresentation = gson.toJson(valueWithQuotes); String jsonRepresentation = gson.toJson(valueWithQuotes);
assertEquals(valueWithQuotes, gson.fromJson(jsonRepresentation, String.class)); assertThat(gson.fromJson(jsonRepresentation, String.class)).isEqualTo(valueWithQuotes);
} }
@Test @Test
public void testEscapedCtrlNInStringSerialization() throws Exception { public void testEscapedCtrlNInStringSerialization() {
String value = "a\nb"; String value = "a\nb";
String json = gson.toJson(value); String json = gson.toJson(value);
assertEquals("\"a\\nb\"", json); assertThat(json).isEqualTo("\"a\\nb\"");
} }
@Test @Test
public void testEscapedCtrlNInStringDeserialization() throws Exception { public void testEscapedCtrlNInStringDeserialization() {
String json = "'a\\nb'"; String json = "'a\\nb'";
String actual = gson.fromJson(json, String.class); String actual = gson.fromJson(json, String.class);
assertEquals("a\nb", actual); assertThat(actual).isEqualTo("a\nb");
} }
@Test @Test
public void testEscapedCtrlRInStringSerialization() throws Exception { public void testEscapedCtrlRInStringSerialization() {
String value = "a\rb"; String value = "a\rb";
String json = gson.toJson(value); String json = gson.toJson(value);
assertEquals("\"a\\rb\"", json); assertThat(json).isEqualTo("\"a\\rb\"");
} }
@Test @Test
public void testEscapedCtrlRInStringDeserialization() throws Exception { public void testEscapedCtrlRInStringDeserialization() {
String json = "'a\\rb'"; String json = "'a\\rb'";
String actual = gson.fromJson(json, String.class); String actual = gson.fromJson(json, String.class);
assertEquals("a\rb", actual); assertThat(actual).isEqualTo("a\rb");
} }
@Test @Test
public void testEscapedBackslashInStringSerialization() throws Exception { public void testEscapedBackslashInStringSerialization() {
String value = "a\\b"; String value = "a\\b";
String json = gson.toJson(value); String json = gson.toJson(value);
assertEquals("\"a\\\\b\"", json); assertThat(json).isEqualTo("\"a\\\\b\"");
} }
@Test @Test
public void testEscapedBackslashInStringDeserialization() throws Exception { public void testEscapedBackslashInStringDeserialization() {
String actual = gson.fromJson("'a\\\\b'", String.class); String actual = gson.fromJson("'a\\\\b'", String.class);
assertEquals("a\\b", actual); assertThat(actual).isEqualTo("a\\b");
} }
@Test @Test
public void testSingleQuoteInStringDeserialization() throws Exception { public void testSingleQuoteInStringDeserialization() {
String value = "beforeQuote'afterQuote"; String value = "beforeQuote'afterQuote";
String actual = gson.fromJson("\"" + value + "\"", String.class); String actual = gson.fromJson("\"" + value + "\"", String.class);
assertEquals(value, actual); assertThat(actual).isEqualTo(value);
} }
@Test @Test
public void testEscapingQuotesInStringSerialization() throws Exception { public void testEscapingQuotesInStringSerialization() {
String valueWithQuotes = "beforeQuote\"afterQuote"; String valueWithQuotes = "beforeQuote\"afterQuote";
String jsonRepresentation = gson.toJson(valueWithQuotes); String jsonRepresentation = gson.toJson(valueWithQuotes);
String target = gson.fromJson(jsonRepresentation, String.class); String target = gson.fromJson(jsonRepresentation, String.class);
assertEquals(valueWithQuotes, target); assertThat(target).isEqualTo(valueWithQuotes);
} }
@Test @Test
public void testEscapingQuotesInStringDeserialization() throws Exception { public void testEscapingQuotesInStringDeserialization() {
String value = "beforeQuote\\\"afterQuote"; String value = "beforeQuote\\\"afterQuote";
String actual = gson.fromJson("\"" + value + "\"", String.class); String actual = gson.fromJson("\"" + value + "\"", String.class);
String expected = "beforeQuote\"afterQuote"; String expected = "beforeQuote\"afterQuote";
assertEquals(expected, actual); assertThat(actual).isEqualTo(expected);
} }
@Test @Test
public void testStringValueAsSingleElementArraySerialization() throws Exception { public void testStringValueAsSingleElementArraySerialization() {
String[] target = {"abc"}; String[] target = {"abc"};
assertEquals("[\"abc\"]", gson.toJson(target)); assertThat(gson.toJson(target)).isEqualTo("[\"abc\"]");
assertEquals("[\"abc\"]", gson.toJson(target, String[].class)); assertThat(gson.toJson(target, String[].class)).isEqualTo("[\"abc\"]");
} }
@Test @Test
@ -116,7 +132,7 @@ public class StringTest {
String value = "/"; String value = "/";
String json = "'\\/'"; String json = "'\\/'";
String actual = gson.fromJson(json, String.class); String actual = gson.fromJson(json, String.class);
assertEquals(value, actual); assertThat(actual).isEqualTo(value);
} }
/** /**
@ -126,7 +142,7 @@ public class StringTest {
public void testAssignmentCharSerialization() { public void testAssignmentCharSerialization() {
String value = "abc="; String value = "abc=";
String json = gson.toJson(value); String json = gson.toJson(value);
assertEquals("\"abc\\u003d\"", json); assertThat(json).isEqualTo("\"abc\\u003d\"");
} }
/** /**
@ -136,24 +152,24 @@ public class StringTest {
public void testAssignmentCharDeserialization() { public void testAssignmentCharDeserialization() {
String json = "\"abc=\""; String json = "\"abc=\"";
String value = gson.fromJson(json, String.class); String value = gson.fromJson(json, String.class);
assertEquals("abc=", value); assertThat(value).isEqualTo("abc=");
json = "'abc\u003d'"; json = "'abc\u003d'";
value = gson.fromJson(json, String.class); value = gson.fromJson(json, String.class);
assertEquals("abc=", value); assertThat(value).isEqualTo("abc=");
} }
@Test @Test
public void testJavascriptKeywordsInStringSerialization() { public void testJavascriptKeywordsInStringSerialization() {
String value = "null true false function"; String value = "null true false function";
String json = gson.toJson(value); String json = gson.toJson(value);
assertEquals("\"" + value + "\"", json); assertThat(json).isEqualTo("\"" + value + "\"");
} }
@Test @Test
public void testJavascriptKeywordsInStringDeserialization() { public void testJavascriptKeywordsInStringDeserialization() {
String json = "'null true false function'"; String json = "'null true false function'";
String value = gson.fromJson(json, String.class); String value = gson.fromJson(json, String.class);
assertEquals(json.substring(1, json.length() - 1), value); assertThat(json.substring(1, json.length() - 1)).isEqualTo(value);
} }
} }

View File

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

View File

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

View File

@ -16,7 +16,7 @@
package com.google.gson.functional; package com.google.gson.functional;
import static org.junit.Assert.assertEquals; import static com.google.common.truth.Truth.assertThat;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;
@ -43,8 +43,8 @@ public final class TypeAdapterPrecedenceTest {
.registerTypeAdapter(Foo.class, newDeserializer("deserializer 1")) .registerTypeAdapter(Foo.class, newDeserializer("deserializer 1"))
.registerTypeAdapter(Foo.class, newDeserializer("deserializer 2")) .registerTypeAdapter(Foo.class, newDeserializer("deserializer 2"))
.create(); .create();
assertEquals("\"foo via serializer 2\"", gson.toJson(new Foo("foo"))); assertThat(gson.toJson(new Foo("foo"))).isEqualTo("\"foo via serializer 2\"");
assertEquals("foo via deserializer 2", gson.fromJson("foo", Foo.class).name); assertThat(gson.fromJson("foo", Foo.class).name).isEqualTo("foo via deserializer 2");
} }
@Test @Test
@ -54,8 +54,8 @@ public final class TypeAdapterPrecedenceTest {
.registerTypeAdapter(Foo.class, newTypeAdapter("type adapter 1")) .registerTypeAdapter(Foo.class, newTypeAdapter("type adapter 1"))
.registerTypeAdapter(Foo.class, newTypeAdapter("type adapter 2")) .registerTypeAdapter(Foo.class, newTypeAdapter("type adapter 2"))
.create(); .create();
assertEquals("\"foo via type adapter 2\"", gson.toJson(new Foo("foo"))); assertThat(gson.toJson(new Foo("foo"))).isEqualTo("\"foo via type adapter 2\"");
assertEquals("foo via type adapter 2", gson.fromJson("foo", Foo.class).name); assertThat(gson.fromJson("foo", Foo.class).name).isEqualTo("foo via type adapter 2");
} }
@Test @Test
@ -66,8 +66,8 @@ public final class TypeAdapterPrecedenceTest {
.registerTypeAdapter(Foo.class, newDeserializer("deserializer")) .registerTypeAdapter(Foo.class, newDeserializer("deserializer"))
.registerTypeAdapter(Foo.class, newTypeAdapter("type adapter")) .registerTypeAdapter(Foo.class, newTypeAdapter("type adapter"))
.create(); .create();
assertEquals("\"foo via type adapter\"", gson.toJson(new Foo("foo"))); assertThat(gson.toJson(new Foo("foo"))).isEqualTo("\"foo via type adapter\"");
assertEquals("foo via type adapter", gson.fromJson("foo", Foo.class).name); assertThat(gson.fromJson("foo", Foo.class).name).isEqualTo("foo via type adapter");
} }
@Test @Test
@ -78,8 +78,8 @@ public final class TypeAdapterPrecedenceTest {
.registerTypeAdapter(Foo.class, newSerializer("serializer")) .registerTypeAdapter(Foo.class, newSerializer("serializer"))
.registerTypeAdapter(Foo.class, newDeserializer("deserializer")) .registerTypeAdapter(Foo.class, newDeserializer("deserializer"))
.create(); .create();
assertEquals("\"foo via serializer\"", gson.toJson(new Foo("foo"))); assertThat(gson.toJson(new Foo("foo"))).isEqualTo("\"foo via serializer\"");
assertEquals("foo via deserializer", gson.fromJson("foo", Foo.class).name); assertThat( gson.fromJson("foo", Foo.class).name).isEqualTo("foo via deserializer");
} }
@Test @Test
@ -90,8 +90,8 @@ public final class TypeAdapterPrecedenceTest {
.registerTypeAdapter(Foo.class, newSerializer("serializer")) .registerTypeAdapter(Foo.class, newSerializer("serializer"))
.registerTypeAdapter(Foo.class, newDeserializer("deserializer")) .registerTypeAdapter(Foo.class, newDeserializer("deserializer"))
.create(); .create();
assertEquals("\"foo via serializer\"", gson.toJson(new Foo("foo"))); assertThat(gson.toJson(new Foo("foo"))).isEqualTo("\"foo via serializer\"");
assertEquals("foo via deserializer", gson.fromJson("foo", Foo.class).name); assertThat(gson.fromJson("foo", Foo.class).name).isEqualTo("foo via deserializer");
} }
@Test @Test
@ -101,8 +101,8 @@ public final class TypeAdapterPrecedenceTest {
.registerTypeHierarchyAdapter(Foo.class, newSerializer("serializer")) .registerTypeHierarchyAdapter(Foo.class, newSerializer("serializer"))
.registerTypeHierarchyAdapter(Foo.class, newDeserializer("deserializer")) .registerTypeHierarchyAdapter(Foo.class, newDeserializer("deserializer"))
.create(); .create();
assertEquals("\"foo via type adapter\"", gson.toJson(new Foo("foo"))); assertThat(gson.toJson(new Foo("foo"))).isEqualTo("\"foo via type adapter\"");
assertEquals("foo via type adapter", gson.fromJson("\"foo\"", Foo.class).name); assertThat(gson.fromJson("\"foo\"", Foo.class).name).isEqualTo("foo via type adapter");
} }
@Test @Test
@ -113,8 +113,8 @@ public final class TypeAdapterPrecedenceTest {
.registerTypeHierarchyAdapter(Foo.class, newDeserializer("deserializer")) .registerTypeHierarchyAdapter(Foo.class, newDeserializer("deserializer"))
.registerTypeHierarchyAdapter(Foo.class, newTypeAdapter("type adapter")) .registerTypeHierarchyAdapter(Foo.class, newTypeAdapter("type adapter"))
.create(); .create();
assertEquals("\"foo via type adapter\"", gson.toJson(new Foo("foo"))); assertThat(gson.toJson(new Foo("foo"))).isEqualTo("\"foo via type adapter\"");
assertEquals("foo via type adapter", gson.fromJson("foo", Foo.class).name); assertThat(gson.fromJson("foo", Foo.class).name).isEqualTo("foo via type adapter");
} }
@Test @Test
@ -126,8 +126,8 @@ public final class TypeAdapterPrecedenceTest {
.registerTypeAdapter(Foo.class, newSerializer("non hierarchical")) .registerTypeAdapter(Foo.class, newSerializer("non hierarchical"))
.registerTypeAdapter(Foo.class, newDeserializer("non hierarchical")) .registerTypeAdapter(Foo.class, newDeserializer("non hierarchical"))
.create(); .create();
assertEquals("\"foo via non hierarchical\"", gson.toJson(new Foo("foo"))); assertThat(gson.toJson(new Foo("foo"))).isEqualTo("\"foo via non hierarchical\"");
assertEquals("foo via non hierarchical", gson.fromJson("foo", Foo.class).name); assertThat(gson.fromJson("foo", Foo.class).name).isEqualTo("foo via non hierarchical");
} }
private static class Foo { private static class Foo {

View File

@ -1,6 +1,22 @@
/*
* Copyright (C) 2022 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.gson.functional; package com.google.gson.functional;
import static org.junit.Assert.assertEquals; import static com.google.common.truth.Truth.assertThat;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;
@ -51,7 +67,7 @@ public class TypeAdapterRuntimeTypeWrapperTest {
.create(); .create();
String json = gson.toJson(new Container()); String json = gson.toJson(new Container());
assertEquals("{\"b\":\"serializer\"}", json); assertThat(json).isEqualTo("{\"b\":\"serializer\"}");
} }
/** /**
@ -66,7 +82,7 @@ public class TypeAdapterRuntimeTypeWrapperTest {
.create(); .create();
String json = gson.toJson(new Container()); String json = gson.toJson(new Container());
assertEquals("{\"b\":{\"f\":\"test\"}}", json); assertThat(json).isEqualTo("{\"b\":{\"f\":\"test\"}}");
} }
/** /**
@ -92,7 +108,7 @@ public class TypeAdapterRuntimeTypeWrapperTest {
.create(); .create();
String json = gson.toJson(new Container()); String json = gson.toJson(new Container());
assertEquals("{\"b\":\"custom delegate\"}", json); assertThat(json).isEqualTo("{\"b\":\"custom delegate\"}");
} }
/** /**
@ -109,7 +125,7 @@ public class TypeAdapterRuntimeTypeWrapperTest {
.create(); .create();
String json = gson.toJson(new Container()); String json = gson.toJson(new Container());
assertEquals("{\"b\":{\"f\":\"test\"}}", json); assertThat(json).isEqualTo("{\"b\":{\"f\":\"test\"}}");
} }
/** /**
@ -131,7 +147,7 @@ public class TypeAdapterRuntimeTypeWrapperTest {
.create(); .create();
String json = gson.toJson(new Container()); String json = gson.toJson(new Container());
assertEquals("{\"b\":\"custom delegate\"}", json); assertThat(json).isEqualTo("{\"b\":\"custom delegate\"}");
} }
/** /**
@ -160,7 +176,7 @@ public class TypeAdapterRuntimeTypeWrapperTest {
.create(); .create();
String json = gson.toJson(new Container()); String json = gson.toJson(new Container());
assertEquals("{\"b\":{\"f\":\"test\"}}", json); assertThat(json).isEqualTo("{\"b\":{\"f\":\"test\"}}");
} }
private static class CyclicBase { private static class CyclicBase {
@ -188,6 +204,6 @@ public class TypeAdapterRuntimeTypeWrapperTest {
CyclicBase b = new CyclicBase(); CyclicBase b = new CyclicBase();
b.f = new CyclicSub(2); b.f = new CyclicSub(2);
String json = new Gson().toJson(b); String json = new Gson().toJson(b);
assertEquals("{\"f\":{\"i\":2}}", json); assertThat(json).isEqualTo("{\"f\":{\"i\":2}}");
} }
} }

Some files were not shown because too many files have changed in this diff Show More