Skip to content

Commit

Permalink
Improve tests
Browse files Browse the repository at this point in the history
  • Loading branch information
Marcono1234 committed May 26, 2024
1 parent 7bbea12 commit f01d394
Show file tree
Hide file tree
Showing 14 changed files with 79 additions and 53 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -173,8 +173,8 @@ private RuntimeTypeAdapterFactory(Class<?> baseType, String typeFieldName, boole
}

/**
* Creates a new runtime type adapter using for {@code baseType} using {@code typeFieldName} as
* the type field name. Type field names are case sensitive.
* Creates a new runtime type adapter for {@code baseType} using {@code typeFieldName} as the type
* field name. Type field names are case sensitive.
*
* @param maintainType true if the type field should be included in deserialized objects
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,8 @@ public void setUp() throws Exception {

@Test
public void testExceptionsPropagated() {
assertThrows(JsonParseException.class, () -> gson.fromJson("{}", User.class));
var e = assertThrows(JsonParseException.class, () -> gson.fromJson("{}", User.class));
assertThat(e).hasMessageThat().isEqualTo("name and password are required fields.");
}

@Test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -91,8 +91,8 @@ public void testWellFormedParseException() {
assertThrows(
JsonParseException.class, () -> gson.fromJson("2017-06-20T14:32:30", Date.class));
assertThat(e)
.hasCauseThat()
.hasMessageThat()
.isEqualTo("Failed to parse date ['2017-06-20T14']: 2017-06-20T14");
.isEqualTo(
"java.text.ParseException: Failed to parse date ['2017-06-20T14']: 2017-06-20T14");
}
}
18 changes: 12 additions & 6 deletions gson/src/test/java/com/google/gson/GsonTypeAdapterTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -45,18 +45,20 @@ public void setUp() throws Exception {
}

@Test
public void testDefaultTypeAdapterThrowsParseException() throws Exception {
public void testDefaultTypeAdapterThrowsParseException() {
assertThrows(JsonParseException.class, () -> gson.fromJson("{\"abc\":123}", BigInteger.class));
}

@Test
public void testTypeAdapterThrowsException() throws Exception {
assertThrows(IllegalStateException.class, () -> gson.toJson(new AtomicLong(0)));
public void testTypeAdapterThrowsException() {
Exception e = assertThrows(IllegalStateException.class, () -> gson.toJson(new AtomicLong(0)));
assertThat(e).isSameInstanceAs(ExceptionTypeAdapter.thrownException);

// Verify that serializer is made null-safe, i.e. it is not called for null
assertThat(gson.toJson(null, AtomicLong.class)).isEqualTo("null");

assertThrows(JsonParseException.class, () -> gson.fromJson("123", AtomicLong.class));
e = assertThrows(JsonParseException.class, () -> gson.fromJson("123", AtomicLong.class));
assertThat(e).hasCauseThat().isSameInstanceAs(ExceptionTypeAdapter.thrownException);

// Verify that deserializer is made null-safe, i.e. it is not called for null
assertThat(gson.fromJson(JsonNull.INSTANCE, AtomicLong.class)).isNull();
Expand Down Expand Up @@ -85,16 +87,20 @@ public void testTypeAdapterDoesNotAffectNonAdaptedTypes() {

private static class ExceptionTypeAdapter
implements JsonSerializer<AtomicLong>, JsonDeserializer<AtomicLong> {
@SuppressWarnings("StaticAssignmentOfThrowable")
static final IllegalStateException thrownException =
new IllegalStateException("test-exception");

@Override
public JsonElement serialize(AtomicLong src, Type typeOfSrc, JsonSerializationContext context) {
throw new IllegalStateException();
throw thrownException;
}

@Override
public AtomicLong deserialize(
JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
throw new IllegalStateException("test-exception");
throw thrownException;
}
}

Expand Down
26 changes: 13 additions & 13 deletions gson/src/test/java/com/google/gson/functional/Java17RecordTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -144,9 +144,9 @@ record LocalRecord(String s) {

/** Tests behavior when the canonical constructor throws an exception */
@Test
@SuppressWarnings("StaticAssignmentOfThrowable")
public void testThrowingConstructor() {
record LocalRecord(String s) {
@SuppressWarnings("StaticAssignmentOfThrowable")
static final RuntimeException thrownException = new RuntimeException("Custom exception");

@SuppressWarnings("unused")
Expand All @@ -157,13 +157,13 @@ record LocalRecord(String s) {

// TODO: Adjust this once Gson throws more specific exception type
var e = assertThrows(RuntimeException.class, () -> gson.fromJson("{\"s\":\"value\"}", LocalRecord.class));
assertThat(e)
.hasMessageThat()
.isEqualTo(
"Failed to invoke constructor '"
+ LocalRecord.class.getName()
+ "(String)' with args [value]");
assertThat(e).hasCauseThat().isSameInstanceAs(LocalRecord.thrownException);
assertThat(e)
.hasMessageThat()
.isEqualTo(
"Failed to invoke constructor '"
+ LocalRecord.class.getName()
+ "(String)' with args [value]");
assertThat(e).hasCauseThat().isSameInstanceAs(LocalRecord.thrownException);
}

@Test
Expand All @@ -180,9 +180,9 @@ public String s() {

/** Tests behavior when a record accessor method throws an exception */
@Test
@SuppressWarnings("StaticAssignmentOfThrowable")
public void testThrowingAccessor() {
record LocalRecord(String s) {
@SuppressWarnings("StaticAssignmentOfThrowable")
static final RuntimeException thrownException = new RuntimeException("Custom exception");

@Override
Expand All @@ -192,10 +192,10 @@ public String s() {
}

var e = assertThrows(JsonIOException.class, () -> gson.toJson(new LocalRecord("a")));
assertThat(e)
.hasMessageThat()
.isEqualTo("Accessor method '" + LocalRecord.class.getName() + "#s()' threw exception");
assertThat(e).hasCauseThat().isSameInstanceAs(LocalRecord.thrownException);
assertThat(e)
.hasMessageThat()
.isEqualTo("Accessor method '" + LocalRecord.class.getName() + "#s()' threw exception");
assertThat(e).hasCauseThat().isSameInstanceAs(LocalRecord.thrownException);
}

/** Tests behavior for a record without components */
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
import com.google.gson.common.TestTypes.BagOfPrimitives;
import com.google.gson.common.TestTypes.Nested;
import com.google.gson.reflect.TypeToken;
import java.io.EOFException;
import java.io.StringReader;
import java.lang.reflect.Type;
import java.util.Arrays;
Expand All @@ -53,7 +54,8 @@ public void setUp() throws Exception {

@Test
public void testParseInvalidJson() {
assertThrows(JsonSyntaxException.class, () -> gson.fromJson("[[]", Object[].class));
var e = assertThrows(JsonSyntaxException.class, () -> gson.fromJson("[[]", Object[].class));
assertThat(e).hasCauseThat().isInstanceOf(EOFException.class);
}

@Test
Expand Down Expand Up @@ -131,6 +133,10 @@ public void testExtraCommasInArrays() {
@Test
public void testExtraCommasInMaps() {
Type type = new TypeToken<Map<String, String>>() {}.getType();
assertThrows(JsonParseException.class, () -> gson.fromJson("{a:b,}", type));
var e = assertThrows(JsonSyntaxException.class, () -> gson.fromJson("{a:b,}", type));
assertThat(e)
.hasCauseThat()
.hasMessageThat()
.startsWith("Expected name at line 1 column 7 path $.");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,8 @@ public void testTwoTypesCollapseToOneSerialize() {
original.put(1.0D, "a");
original.put(1.0F, "b");
Type type = new TypeToken<Map<Number, String>>() {}.getType();
assertThrows(JsonSyntaxException.class, () -> gson.toJson(original, type));
var e = assertThrows(JsonSyntaxException.class, () -> gson.toJson(original, type));
assertThat(e).hasMessageThat().isEqualTo("TODO");
}

@Test
Expand Down
6 changes: 4 additions & 2 deletions gson/src/test/java/com/google/gson/functional/ObjectTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@
import com.google.gson.common.TestTypes.Nested;
import com.google.gson.common.TestTypes.PrimitiveArray;
import com.google.gson.reflect.TypeToken;
import java.io.EOFException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
Expand Down Expand Up @@ -241,7 +242,8 @@ public void testEmptyStringDeserialization() {
@Test
public void testTruncatedDeserialization() {
Type type = new TypeToken<List<String>>() {}.getType();
assertThrows(JsonParseException.class, () -> gson.fromJson("[\"a\", \"b\",", type));
var e = assertThrows(JsonParseException.class, () -> gson.fromJson("[\"a\", \"b\",", type));
assertThat(e).hasCauseThat().isInstanceOf(EOFException.class);
}

@Test
Expand Down Expand Up @@ -757,8 +759,8 @@ public void testThrowingDefaultConstructor() {
assertThat(e).hasCauseThat().isSameInstanceAs(ClassWithThrowingConstructor.thrownException);
}

@SuppressWarnings("StaticAssignmentOfThrowable")
static class ClassWithThrowingConstructor {
@SuppressWarnings("StaticAssignmentOfThrowable")
static final RuntimeException thrownException = new RuntimeException("Custom exception");

public ClassWithThrowingConstructor() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -732,7 +732,7 @@ public void testNegativeInfinityFloatDeserialization() {

@Test
public void testBigDecimalNegativeInfinityDeserializationNotSupported() {
// Gson should not accept positive infinity for deserialization
// Gson should not accept negative infinity for deserialization
assertThrows(JsonSyntaxException.class, () -> gson.fromJson("-Infinity", BigDecimal.class));
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -132,13 +132,23 @@ public void testReadWriteTwoObjects() throws IOException {
@Test
public void testTypeMismatchThrowsJsonSyntaxExceptionForStrings() {
Type type = new TypeToken<Map<String, String>>() {}.getType();
assertThrows(JsonSyntaxException.class, () -> gson.fromJson("true", type));
var e = assertThrows(JsonSyntaxException.class, () -> gson.fromJson("true", type));
assertThat(e)
.hasCauseThat()
.hasMessageThat()
.startsWith("Expected BEGIN_OBJECT but was BOOLEAN");
}

@Test
public void testTypeMismatchThrowsJsonSyntaxExceptionForReaders() {
Type type = new TypeToken<Map<String, String>>() {}.getType();
assertThrows(JsonSyntaxException.class, () -> gson.fromJson(new StringReader("true"), type));
var e =
assertThrows(
JsonSyntaxException.class, () -> gson.fromJson(new StringReader("true"), type));
assertThat(e)
.hasCauseThat()
.hasMessageThat()
.startsWith("Expected BEGIN_OBJECT but was BOOLEAN");
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,6 @@ public void write(JsonWriter out, Person person) throws IOException {
truck.passengers = new ArrayList<>();
truck.passengers.add(null);
truck.passengers.add(new Person("jesse", 30));

assertThrows(NullPointerException.class, () -> gson.toJson(truck, Truck.class));

String json = "{horsePower:1.0,passengers:[null,'jesse,30']}";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -262,7 +262,8 @@ public void testNextJsonElement() throws IOException {
JsonTreeReader reader = new JsonTreeReader(element);
reader.beginObject();

assertThrows(IllegalStateException.class, () -> reader.nextJsonElement());
var e = assertThrows(IllegalStateException.class, () -> reader.nextJsonElement());
assertThat(e).hasMessageThat().isEqualTo("Unexpected NAME when reading a JsonElement.");
assertThat(reader.nextName()).isEqualTo("A");
assertThat(new JsonPrimitive(1)).isEqualTo(reader.nextJsonElement());

Expand Down
29 changes: 17 additions & 12 deletions gson/src/test/java/com/google/gson/stream/JsonReaderTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ public void testSetStrictnessNull() {
}

@Test
public void testEscapedNewlineNotAllowedInStrictMode() throws IOException {
public void testEscapedNewlineNotAllowedInStrictMode() {
String json = "\"\\\n\"";
JsonReader reader = new JsonReader(reader(json));
reader.setStrictness(Strictness.STRICT);
Expand Down Expand Up @@ -145,7 +145,7 @@ public void testNonStrictModeParsesUnescapedControlCharacter() throws IOExceptio
}

@Test
public void testCapitalizedTrueFailWhenStrict() throws IOException {
public void testCapitalizedTrueFailWhenStrict() {
JsonReader reader = new JsonReader(reader("TRUE"));
reader.setStrictness(Strictness.STRICT);

Expand All @@ -168,7 +168,7 @@ public void testCapitalizedTrueFailWhenStrict() throws IOException {
}

@Test
public void testCapitalizedFalseFailWhenStrict() throws IOException {
public void testCapitalizedFalseFailWhenStrict() {
JsonReader reader = new JsonReader(reader("FALSE"));
reader.setStrictness(Strictness.STRICT);

Expand All @@ -191,7 +191,7 @@ public void testCapitalizedFalseFailWhenStrict() throws IOException {
}

@Test
public void testCapitalizedNullFailWhenStrict() throws IOException {
public void testCapitalizedNullFailWhenStrict() {
JsonReader reader = new JsonReader(reader("NULL"));
reader.setStrictness(Strictness.STRICT);

Expand Down Expand Up @@ -463,7 +463,7 @@ public void testNulls() {
}

@Test
public void testEmptyString() throws IOException {
public void testEmptyString() {
assertThrows(EOFException.class, () -> new JsonReader(reader("")).beginArray());
assertThrows(EOFException.class, () -> new JsonReader(reader("")).beginObject());
}
Expand Down Expand Up @@ -544,7 +544,7 @@ public void testReaderDoesNotTreatU2028U2029AsNewline() throws IOException {
}

@Test
public void testEscapeCharacterQuoteInStrictMode() throws IOException {
public void testEscapeCharacterQuoteInStrictMode() {
String json = "\"\\'\"";
JsonReader reader = new JsonReader(reader(json));
reader.setStrictness(Strictness.STRICT);
Expand Down Expand Up @@ -907,7 +907,7 @@ public void testNegativeZero() throws Exception {

/**
* This test fails because there's no double for 9223372036854775808, and our long parsing uses
* {@link Double#parseDouble(String)} for fractional values.
* Double.parseDouble() for fractional values.
*/
@Test
@Ignore
Expand Down Expand Up @@ -1371,6 +1371,10 @@ public void testStrictSemicolonDelimitedNameValuePairWithSkipValue() throws IOEx

@Test
public void testStrictUnnecessaryArraySeparators() throws IOException {
// The following calls `nextNull()` because a lenient JsonReader would treat redundant array
// separators as
// implicit JSON null

JsonReader reader = new JsonReader(reader("[true,,true]"));
reader.beginArray();
assertThat(reader.nextBoolean()).isTrue();
Expand Down Expand Up @@ -1400,6 +1404,7 @@ public void testLenientUnnecessaryArraySeparators() throws IOException {
reader.setStrictness(Strictness.LENIENT);
reader.beginArray();
assertThat(reader.nextBoolean()).isTrue();
// Redundant array separators are treated as implicit JSON null
reader.nextNull();
assertThat(reader.nextBoolean()).isTrue();
reader.endArray();
Expand Down Expand Up @@ -1517,14 +1522,14 @@ public void testTopLevelValueTypeWithSkipValue() throws IOException {
}

@Test
public void testStrictNonExecutePrefix() throws IOException {
public void testStrictNonExecutePrefix() {
JsonReader reader = new JsonReader(reader(")]}'\n []"));
var e = assertThrows(MalformedJsonException.class, () -> reader.beginArray());
assertStrictError(e, "line 1 column 1 path $");
}

@Test
public void testStrictNonExecutePrefixWithSkipValue() throws IOException {
public void testStrictNonExecutePrefixWithSkipValue() {
JsonReader reader = new JsonReader(reader(")]}'\n []"));
var e = assertThrows(MalformedJsonException.class, () -> reader.skipValue());
assertStrictError(e, "line 1 column 1 path $");
Expand Down Expand Up @@ -1750,7 +1755,7 @@ public void testDeeplyNestedObjects() throws IOException {

// http://code.google.com/p/google-gson/issues/detail?id=409
@Test
public void testStringEndingInSlash() throws IOException {
public void testStringEndingInSlash() {
JsonReader reader = new JsonReader(reader("/"));
reader.setStrictness(Strictness.LENIENT);
var e = assertThrows(MalformedJsonException.class, () -> reader.peek());
Expand All @@ -1762,7 +1767,7 @@ public void testStringEndingInSlash() throws IOException {
}

@Test
public void testDocumentWithCommentEndingInSlash() throws IOException {
public void testDocumentWithCommentEndingInSlash() {
JsonReader reader = new JsonReader(reader("/* foo *//"));
reader.setStrictness(Strictness.LENIENT);
var e = assertThrows(MalformedJsonException.class, () -> reader.peek());
Expand All @@ -1774,7 +1779,7 @@ public void testDocumentWithCommentEndingInSlash() throws IOException {
}

@Test
public void testStringWithLeadingSlash() throws IOException {
public void testStringWithLeadingSlash() {
JsonReader reader = new JsonReader(reader("/x"));
reader.setStrictness(Strictness.LENIENT);
var e = assertThrows(MalformedJsonException.class, () -> reader.peek());
Expand Down
Loading

0 comments on commit f01d394

Please sign in to comment.