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">
<modelVersion>4.0.0</modelVersion>
@ -29,6 +45,12 @@
<version>1.1.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava-testlib</artifactId>
<version>31.1-jre</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
@ -103,7 +125,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M8</version>
<version>3.0.0-M9</version>
<configuration>
<!-- Deny illegal access, this is required for ReflectionAccessTest -->
<!-- Requires Java >= 9; Important: In case future Java versions

View File

@ -93,12 +93,16 @@ package com.google.gson;
public interface ExclusionStrategy {
/**
* Decides if a field should be skipped during serialization or deserialization.
*
* @param f the field object that is under test
* @return true if the field should be ignored; otherwise false
*/
public boolean shouldSkipField(FieldAttributes f);
/**
* Decides if a class should be serialized or deserialized
*
* @param clazz the class object that is under test
* @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
*/
public Class<?> getDeclaringClass() {
@ -53,6 +55,8 @@ public final class FieldAttributes {
}
/**
* Gets the name of the field
*
* @return the name of the field
*/
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
* 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
* {@link JsonSerializer}s, {@link JsonDeserializer}s, and {@link InstanceCreator}s.</p>
* configuration options such as versioning support, pretty printing, custom newline, custom indent,
* 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:
*
@ -146,6 +146,7 @@ public final class Gson {
* with the type token provided to {@code getAdapter} as key and either
* {@code FutureTypeAdapter} or a regular {@code TypeAdapter} as value.
*/
@SuppressWarnings("ThreadLocalUsage")
private final ThreadLocal<Map<TypeToken<?>, TypeAdapter<?>>> threadLocalAdapterResults = new ThreadLocal<>();
private final ConcurrentMap<TypeToken<?>, TypeAdapter<?>> typeTokenCache = new ConcurrentHashMap<>();
@ -163,7 +164,7 @@ public final class Gson {
final boolean duplicateMapKeyDeserialization;
final boolean generateNonExecutableJson;
final boolean htmlSafe;
final boolean prettyPrinting;
final FormattingStyle formattingStyle;
final boolean lenient;
final boolean omitQuotes;
final boolean serializeSpecialFloatingPointValues;
@ -184,7 +185,9 @@ public final class Gson {
* <ul>
* <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
* {@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
* 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
@ -216,7 +219,7 @@ public final class Gson {
this(Excluder.DEFAULT, DefaultConfig.DEFAULT_FIELD_NAMING_STRATEGY,
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_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,
LongSerializationPolicy.DEFAULT, DefaultConfig.DEFAULT_DATE_PATTERN, DateFormat.DEFAULT, DateFormat.DEFAULT,
Collections.<TypeAdapterFactory>emptyList(), Collections.<TypeAdapterFactory>emptyList(),
@ -227,7 +230,7 @@ public final class Gson {
Gson(Excluder excluder, FieldNamingStrategy fieldNamingStrategy,
Map<Type, InstanceCreator<?>> instanceCreators, boolean serializeNulls,
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,
LongSerializationPolicy longSerializationPolicy, String datePattern, int dateStyle,
int timeStyle, List<TypeAdapterFactory> builderFactories,
@ -244,7 +247,7 @@ public final class Gson {
this.duplicateMapKeyDeserialization = duplicateMapKeyDeserialization;
this.generateNonExecutableJson = generateNonExecutableGson;
this.htmlSafe = htmlSafe;
this.prettyPrinting = prettyPrinting;
this.formattingStyle = formattingStyle;
this.lenient = lenient;
this.omitQuotes = omitQuotes;
this.serializeSpecialFloatingPointValues = serializeSpecialFloatingPointValues;
@ -677,7 +680,7 @@ public final class Gson {
* <pre>
* Type typeOfSrc = new TypeToken&lt;Collection&lt;Foo&gt;&gt;(){}.getType();
* </pre>
* @return Json representation of {@code src}
* @return JSON representation of {@code src}.
* @since 1.4
*
* @see #toJsonTree(Object)
@ -699,7 +702,7 @@ public final class Gson {
* {@link Writer}, use {@link #toJson(Object, Appendable)} instead.
*
* @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, Type)
@ -724,7 +727,7 @@ public final class Gson {
* <pre>
* Type typeOfSrc = new TypeToken&lt;Collection&lt;Foo&gt;&gt;(){}.getType();
* </pre>
* @return JSON representation of {@code src}
* @return JSON representation of {@code src}.
*
* @see #toJson(Object, Type, Appendable)
* @see #toJson(Object)
@ -833,7 +836,7 @@ public final class Gson {
* Converts a tree of {@link JsonElement}s into its equivalent JSON representation.
*
* @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
*/
public String toJson(JsonElement jsonElement) {
@ -870,6 +873,7 @@ public final class Gson {
* <li>{@link GsonBuilder#setLenient()}</li>
* <li>{@link GsonBuilder#setOmitQuotes()}</li>
* <li>{@link GsonBuilder#setPrettyPrinting()}</li>
* <li>{@link GsonBuilder#setPrettyPrinting(FormattingStyle)}</li>
* </ul>
*/
public JsonWriter newJsonWriter(Writer writer) throws IOException {
@ -877,9 +881,7 @@ public final class Gson {
writer.write(DefaultConfig.JSON_NON_EXECUTABLE_PREFIX);
}
JsonWriter jsonWriter = new JsonWriter(writer);
if (prettyPrinting) {
jsonWriter.setIndent(" ");
}
jsonWriter.setFormattingStyle(formattingStyle);
jsonWriter.setHtmlSafe(htmlSafe);
jsonWriter.setLenient(lenient);
jsonWriter.setOmitQuotes(omitQuotes);

View File

@ -31,11 +31,11 @@ import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.lang.reflect.Type;
import java.text.DateFormat;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
@ -89,14 +89,14 @@ public final class GsonBuilder {
private boolean duplicateMapKeyDeserialization = DEFAULT_DUPLICATE_MAP_KEYS;
private boolean serializeSpecialFloatingPointValues = DEFAULT_SPECIALIZE_FLOAT_VALUES;
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 lenient = DEFAULT_LENIENT;
private boolean omitQuotes = DEFAULT_OMIT_QUOTES;
private boolean useJdkUnsafe = DEFAULT_USE_JDK_UNSAFE;
private ToNumberStrategy objectToNumberStrategy = DEFAULT_OBJECT_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
@ -122,7 +122,7 @@ public final class GsonBuilder {
this.duplicateMapKeyDeserialization = gson.duplicateMapKeyDeserialization;
this.generateNonExecutableJson = gson.generateNonExecutableJson;
this.escapeHtmlChars = gson.htmlSafe;
this.prettyPrinting = gson.prettyPrinting;
this.formattingStyle = gson.formattingStyle;
this.lenient = gson.lenient;
this.omitQuotes = gson.omitQuotes;
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
* affects Json serialization.
* Configures Gson to output JSON that fits in a page for pretty printing. This option only
* affects JSON serialization.
*
* @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern
*/
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;
}
@ -780,7 +793,7 @@ public final class GsonBuilder {
return new Gson(excluder, fieldNamingPolicy, new HashMap<>(instanceCreators),
serializeNulls, complexMapKeySerialization, duplicateMapKeyDeserialization,
generateNonExecutableJson, escapeHtmlChars, prettyPrinting, lenient, omitQuotes,
generateNonExecutableJson, escapeHtmlChars, formattingStyle, lenient, omitQuotes,
serializeSpecialFloatingPointValues, useJdkUnsafe, longSerializationPolicy,
datePattern, dateStyle, timeStyle, new ArrayList<>(this.factories),
new ArrayList<>(this.hierarchyFactories), factories,

View File

@ -89,7 +89,7 @@ public interface JsonDeserializer<T> {
* @param json The Json data being deserialized
* @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}
* @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)
throws JsonParseException;

View File

@ -106,7 +106,7 @@ public final class JsonPrimitive extends JsonElement {
if (isBoolean()) {
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());
}
@ -180,8 +180,11 @@ public final class JsonPrimitive extends JsonElement {
*/
@Override
public BigInteger getAsBigInteger() {
return value instanceof BigInteger ?
(BigInteger) value : new BigInteger(getAsString());
return value instanceof BigInteger
? (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;
}
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) {
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;
import com.google.gson.internal.ReflectionAccessFilterHelper;

View File

@ -83,10 +83,14 @@ import java.lang.annotation.Target;
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
*/
String value();
/**
* The alternative names of the field when it is deserialized
*
* @return the alternative names of the field when it is deserialized
*/
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}.
*
* @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<>();
}
};
} else if (type instanceof ParameterizedType && !(String.class.isAssignableFrom(
TypeToken.get(((ParameterizedType) type).getActualTypeArguments()[0]).getRawType()))) {
} else if (type instanceof ParameterizedType && !String.class.isAssignableFrom(
TypeToken.get(((ParameterizedType) type).getActualTypeArguments()[0]).getRawType())) {
return new ObjectConstructor<T>() {
@Override public T construct() {
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_LENIENT = 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_SERIALIZE_NULLS = 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.
*/
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.
*/
public static boolean isJava9OrLater() {

View File

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

View File

@ -304,6 +304,7 @@ public final class LinkedTreeMap<K, V> extends AbstractMap<K, V> implements Seri
return node;
}
@SuppressWarnings("ReferenceEquality")
private void replaceInParent(Node<K, V> node, Node<K, V> replacement) {
Node<K, V> parent = node.parent;
node.parent = null;
@ -315,7 +316,7 @@ public final class LinkedTreeMap<K, V> extends AbstractMap<K, V> implements Seri
if (parent.left == node) {
parent.left = replacement;
} else {
assert (parent.right == node);
assert parent.right == node;
parent.right = replacement;
}
} else {
@ -559,10 +560,13 @@ public final class LinkedTreeMap<K, V> extends AbstractMap<K, V> implements Seri
LinkedTreeMapIterator() {
}
@Override public final boolean hasNext() {
@Override
@SuppressWarnings("ReferenceEquality")
public final boolean hasNext() {
return next != header;
}
@SuppressWarnings("ReferenceEquality")
final Node<K, V> nextNode() {
Node<K, V> e = next;
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;
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;
import java.lang.reflect.AccessibleObject;
@ -82,6 +98,7 @@ public class ReflectionAccessFilterHelper {
}
};
} catch (NoSuchMethodException ignored) {
// OK: will assume everything is accessible
}
}

View File

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

View File

@ -37,7 +37,7 @@ public final class ArrayTypeAdapter<E> extends TypeAdapter<Object> {
public static final TypeAdapterFactory FACTORY = new TypeAdapterFactory() {
@Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
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;
}

View File

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

View File

@ -154,7 +154,9 @@ public final class DefaultDateTypeAdapter<T extends Date> extends TypeAdapter<T>
for (DateFormat dateFormat : dateFormats) {
try {
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;
import com.google.gson.TypeAdapter;

View File

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

View File

@ -42,8 +42,6 @@ import java.net.InetAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.BitSet;
@ -124,7 +122,7 @@ public final class TypeAdapters {
@Override public void write(JsonWriter out, BitSet src) throws IOException {
out.beginArray();
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.endArray();
@ -867,24 +865,22 @@ public final class TypeAdapters {
// 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;
// should be acceptable because this only retrieves enum constants, but does not expose anything else
Field[] constantFields = AccessController.doPrivileged(new PrivilegedAction<Field[]>() {
@Override public Field[] run() {
Field[] fields = classOfT.getDeclaredFields();
ArrayList<Field> constantFieldsList = new ArrayList<>(fields.length);
for (Field f : fields) {
if (f.isEnumConstant()) {
constantFieldsList.add(f);
}
Field[] constantFields;
{
Field[] fields = classOfT.getDeclaredFields();
ArrayList<Field> constantFieldsList = new ArrayList<>(fields.length);
for (Field f : fields) {
if (f.isEnumConstant()) {
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) {
@SuppressWarnings("unchecked")
T constant = (T)(constantField.get(null));
T constant = (T) constantField.get(null);
String name = constant.name();
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.
* These classes will very likely change incompatibly in future versions. You have been warned.
*
* @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;
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;
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;
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
* vice-versa.
@ -8,4 +24,4 @@
*
* @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.
*
* @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.regex.Pattern;
import com.google.gson.FormattingStyle;
/**
* 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
@ -181,10 +183,9 @@ public class JsonWriter implements Closeable, Flushable {
}
/**
* A string containing a full set of spaces for a single level of
* indentation, or null for no pretty printing.
* The settings used for pretty printing, or null for no pretty printing.
*/
private String indent;
private FormattingStyle formattingStyle;
/**
* The name/value separator; either ":" or ": ".
@ -224,14 +225,44 @@ public class JsonWriter implements Closeable, Flushable {
*/
public final void setIndent(String indent) {
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 = ":";
} else {
this.indent = indent;
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
* only emits well-formed JSON as specified by <a
@ -431,7 +462,7 @@ public class JsonWriter implements Closeable, Flushable {
private void writeDeferredComment() throws IOException {
if (!deferredComment.isEmpty()) {
if (indent == null) {
if (formattingStyle == null || formattingStyle.getNewline().isEmpty()) {
out.append("/* ").append(String.join(" / ", deferredComment)).append(" */");
} else {
boolean first = true;
@ -678,7 +709,7 @@ public class JsonWriter implements Closeable, Flushable {
out.close();
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");
}
stackSize = 0;
@ -717,13 +748,13 @@ public class JsonWriter implements Closeable, Flushable {
}
private void newline() throws IOException {
if (indent == null) {
if (formattingStyle == null) {
return;
}
out.write('\n');
out.write(formattingStyle.getNewline());
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.
*/

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;
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.
* @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;
import static com.google.common.truth.Truth.assertThat;

View File

@ -63,7 +63,8 @@ public final class GsonTest {
public void testOverridesDefaultExcluder() {
Gson gson = new Gson(CUSTOM_EXCLUDER, CUSTOM_FIELD_NAMING_STRATEGY,
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>(),
new ArrayList<TypeAdapterFactory>(), new ArrayList<TypeAdapterFactory>(),
CUSTOM_OBJECT_TO_NUMBER_STRATEGY, CUSTOM_NUMBER_TO_NUMBER_STRATEGY,
@ -79,7 +80,8 @@ public final class GsonTest {
public void testClonedTypeAdapterFactoryListsAreIndependent() {
Gson original = new Gson(CUSTOM_EXCLUDER, CUSTOM_FIELD_NAMING_STRATEGY,
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>(),
new ArrayList<TypeAdapterFactory>(), new ArrayList<TypeAdapterFactory>(),
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;
import static com.google.common.truth.Truth.assertThat;
@ -202,9 +218,9 @@ public class JsonArrayAsListTest {
a.add(1);
List<JsonElement> list = a.asList();
assertThat(list.contains(new JsonPrimitive(1))).isTrue();
assertThat(list.contains(new JsonPrimitive(2))).isFalse();
assertThat(list.contains(null)).isFalse();
assertThat(list).contains(new JsonPrimitive(1));
assertThat(list).doesNotContain(new JsonPrimitive(2));
assertThat(list).doesNotContain(null);
@SuppressWarnings({"unlikely-arg-type", "CollectionIncompatibleType"})
boolean containsInt = list.contains(1); // should only contain JsonPrimitive(1)

View File

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

View File

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

View File

@ -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;
import static com.google.common.truth.Truth.assertThat;

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -16,7 +16,7 @@
package com.google.gson.functional;
import static org.junit.Assert.assertEquals;
import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.fail;
import com.google.gson.*;
@ -59,8 +59,8 @@ public class JsonParserTest {
obj.addProperty("stringValue", "foo");
obj.addProperty("intValue", 11);
BagOfPrimitives target = gson.fromJson(obj, BagOfPrimitives.class);
assertEquals(11, target.intValue);
assertEquals("foo", target.stringValue);
assertThat(target.intValue).isEqualTo(11);
assertThat(target.stringValue).isEqualTo("foo");
}
@Test
@ -117,17 +117,17 @@ public class JsonParserTest {
obj.remove("stringValue");
obj.addProperty("stringValue", "fooBar");
BagOfPrimitives target = gson.fromJson(obj, BagOfPrimitives.class);
assertEquals(10, target.intValue);
assertEquals(20, target.longValue);
assertEquals("fooBar", target.stringValue);
assertThat(target.intValue).isEqualTo(10);
assertThat(target.longValue).isEqualTo(20);
assertThat(target.stringValue).isEqualTo("fooBar");
}
@Test
public void testExtraCommasInArrays() {
Type type = new TypeToken<List<String>>() {}.getType();
assertEquals(Arrays.asList("a", "b"), gson.fromJson("[a,,b,,]", type));
assertEquals(Arrays.asList(), gson.fromJson("[,]", type));
assertEquals(Arrays.asList("a"), gson.fromJson("[a,]", type));
assertThat(Arrays.asList("a", "b")).isEqualTo(gson.fromJson("[a,,b,,]", type));
assertThat(Arrays.asList()).isEqualTo(gson.fromJson("[,]", type));
assertThat(Arrays.asList("a")).isEqualTo(gson.fromJson("[a,]", type));
}
@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;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.fail;
import com.google.gson.Gson;
@ -35,10 +49,10 @@ public class JsonTreeTest {
public void testToJsonTree() {
BagOfPrimitives bag = new BagOfPrimitives(10L, 5, false, "foo");
JsonElement json = gson.toJsonTree(bag);
assertTrue(json.isJsonObject());
assertThat(json.isJsonObject()).isTrue();
JsonObject obj = json.getAsJsonObject();
Set<Entry<String, JsonElement>> children = obj.entrySet();
assertEquals(4, children.size());
assertThat(children).hasSize(4);
assertContains(obj, new JsonPrimitive(10L));
assertContains(obj, new JsonPrimitive(5));
assertContains(obj, new JsonPrimitive(false));
@ -49,10 +63,10 @@ public class JsonTreeTest {
public void testToJsonTreeObjectType() {
SubTypeOfBagOfPrimitives bag = new SubTypeOfBagOfPrimitives(10L, 5, false, "foo", 1.4F);
JsonElement json = gson.toJsonTree(bag, BagOfPrimitives.class);
assertTrue(json.isJsonObject());
assertThat(json.isJsonObject()).isTrue();
JsonObject obj = json.getAsJsonObject();
Set<Entry<String, JsonElement>> children = obj.entrySet();
assertEquals(4, children.size());
assertThat(children).hasSize(4);
assertContains(obj, new JsonPrimitive(10L));
assertContains(obj, new JsonPrimitive(5));
assertContains(obj, new JsonPrimitive(false));
@ -65,14 +79,14 @@ public class JsonTreeTest {
String json1 = gson.toJson(bag);
JsonElement jsonElement = gson.toJsonTree(bag, SubTypeOfBagOfPrimitives.class);
String json2 = gson.toJson(jsonElement);
assertEquals(json1, json2);
assertThat(json2).isEqualTo(json1);
}
@Test
public void testJsonTreeNull() {
BagOfPrimitives bag = new BagOfPrimitives(10L, 5, false, null);
JsonObject jsonElement = (JsonObject) gson.toJsonTree(bag, BagOfPrimitives.class);
assertFalse(jsonElement.has("stringValue"));
assertThat(jsonElement.has("stringValue")).isFalse();
}
private void assertContains(JsonObject json, JsonPrimitive child) {

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,8 +1,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;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.fail;
import com.google.gson.Gson;
@ -45,7 +59,7 @@ public class ReflectionAccessTest {
public void testSerializeInternalImplementationObject() {
Gson gson = new Gson();
String json = gson.toJson(Collections.emptyList());
assertEquals("[]", json);
assertThat(json).isEqualTo("[]");
// But deserialization should fail
Class<?> internalClass = Collections.emptyList().getClass();
@ -55,10 +69,8 @@ public class ReflectionAccessTest {
} catch (JsonSyntaxException e) {
fail("Unexpected exception; test has to be run with `--illegal-access=deny`");
} catch (JsonIOException expected) {
assertTrue(expected.getMessage().startsWith(
"Failed making constructor 'java.util.Collections$EmptyList()' accessible;"
+ " either increase its visibility or write a custom InstanceCreator or TypeAdapter for its declaring type: "
));
assertThat(expected).hasMessageThat().startsWith("Failed making constructor 'java.util.Collections$EmptyList()' accessible;"
+ " either increase its visibility or write a custom InstanceCreator or TypeAdapter for its declaring type: ");
}
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

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