From 88632a94c2dc8727eedc8d65b9fdb7b06b045651 Mon Sep 17 00:00:00 2001 From: Marcono1234 Date: Sun, 26 May 2024 19:00:27 +0200 Subject: [PATCH 1/7] Use `assertThrows` for expected exceptions in tests --- .../com/google/gson/FieldAttributesTest.java | 9 +- .../java/com/google/gson/GsonBuilderTest.java | 41 +- .../com/google/gson/GsonTypeAdapterTest.java | 22 +- .../java/com/google/gson/JsonArrayTest.java | 103 +- .../com/google/gson/JsonObjectAsMapTest.java | 74 +- .../java/com/google/gson/JsonObjectTest.java | 24 +- .../com/google/gson/JsonPrimitiveTest.java | 54 +- .../java/com/google/gson/MixedStreamTest.java | 74 +- .../com/google/gson/functional/ArrayTest.java | 10 +- .../functional/CircularReferenceTest.java | 24 +- .../functional/EnumWithObfuscatedTest.java | 11 +- .../gson/functional/FormattingStyleTest.java | 50 +- .../gson/functional/Java17RecordTest.java | 14 +- .../JsonAdapterAnnotationOnClassesTest.java | 18 +- .../gson/functional/JsonParserTest.java | 35 +- .../google/gson/functional/JsonTreeTest.java | 3 +- .../functional/MapAsArrayTypeAdapterTest.java | 19 +- .../com/google/gson/functional/MapTest.java | 21 +- .../gson/functional/NamingPolicyTest.java | 49 +- .../google/gson/functional/ObjectTest.java | 67 +- .../google/gson/functional/PrimitiveTest.java | 211 ++-- .../gson/functional/ReadersWritersTest.java | 17 +- .../ReflectionAccessFilterTest.java | 258 +++-- .../gson/functional/ReflectionAccessTest.java | 18 +- .../functional/StreamingTypeAdaptersTest.java | 43 +- .../ToNumberPolicyFunctionalTest.java | 28 +- .../gson/functional/UncategorizedTest.java | 17 +- .../internal/ConstructorConstructorTest.java | 40 +- .../gson/internal/LinkedTreeMapTest.java | 55 +- .../com/google/gson/internal/StreamsTest.java | 26 +- .../internal/bind/JsonElementReaderTest.java | 171 +--- .../internal/bind/JsonTreeReaderTest.java | 21 +- .../internal/bind/JsonTreeWriterTest.java | 99 +- .../com/google/gson/regression/OSGiTest.java | 16 +- .../google/gson/stream/JsonReaderTest.java | 954 ++++++------------ .../google/gson/stream/JsonWriterTest.java | 113 +-- 36 files changed, 989 insertions(+), 1820 deletions(-) diff --git a/gson/src/test/java/com/google/gson/FieldAttributesTest.java b/gson/src/test/java/com/google/gson/FieldAttributesTest.java index 17a4d70f6e..672fb3fdbc 100644 --- a/gson/src/test/java/com/google/gson/FieldAttributesTest.java +++ b/gson/src/test/java/com/google/gson/FieldAttributesTest.java @@ -17,7 +17,7 @@ package com.google.gson; import static com.google.common.truth.Truth.assertThat; -import static org.junit.Assert.fail; +import static org.junit.Assert.assertThrows; import com.google.gson.reflect.TypeToken; import java.lang.reflect.Modifier; @@ -40,14 +40,9 @@ public void setUp() throws Exception { fieldAttributes = new FieldAttributes(Foo.class.getField("bar")); } - @SuppressWarnings("unused") @Test public void testNullField() { - try { - new FieldAttributes(null); - fail("Field parameter can not be null"); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> new FieldAttributes(null)); } @Test diff --git a/gson/src/test/java/com/google/gson/GsonBuilderTest.java b/gson/src/test/java/com/google/gson/GsonBuilderTest.java index 03cea71947..2d9a63101d 100644 --- a/gson/src/test/java/com/google/gson/GsonBuilderTest.java +++ b/gson/src/test/java/com/google/gson/GsonBuilderTest.java @@ -18,7 +18,6 @@ import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.assertThrows; -import static org.junit.Assert.fail; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; @@ -203,19 +202,17 @@ public void testRegisterTypeAdapterForCoreType() { @Test public void testDisableJdkUnsafe() { Gson gson = new GsonBuilder().disableJdkUnsafe().create(); - try { - gson.fromJson("{}", ClassWithoutNoArgsConstructor.class); - fail("Expected exception"); - } catch (JsonIOException expected) { - assertThat(expected) - .hasMessageThat() - .isEqualTo( - "Unable to create instance of class" - + " com.google.gson.GsonBuilderTest$ClassWithoutNoArgsConstructor; usage of JDK" - + " Unsafe is disabled. Registering an InstanceCreator or a TypeAdapter for this" - + " type, adding a no-args constructor, or enabling usage of JDK Unsafe may fix" - + " this problem."); - } + var e = + assertThrows( + JsonIOException.class, () -> gson.fromJson("{}", ClassWithoutNoArgsConstructor.class)); + assertThat(e) + .hasMessageThat() + .isEqualTo( + "Unable to create instance of class" + + " com.google.gson.GsonBuilderTest$ClassWithoutNoArgsConstructor; usage of JDK" + + " Unsafe is disabled. Registering an InstanceCreator or a TypeAdapter for this" + + " type, adding a no-args constructor, or enabling usage of JDK Unsafe may fix" + + " this problem."); } private static class ClassWithoutNoArgsConstructor { @@ -226,19 +223,11 @@ public ClassWithoutNoArgsConstructor(String s) {} @Test public void testSetVersionInvalid() { GsonBuilder builder = new GsonBuilder(); - try { - builder.setVersion(Double.NaN); - fail(); - } catch (IllegalArgumentException e) { - assertThat(e).hasMessageThat().isEqualTo("Invalid version: NaN"); - } + var e = assertThrows(IllegalArgumentException.class, () -> builder.setVersion(Double.NaN)); + assertThat(e).hasMessageThat().isEqualTo("Invalid version: NaN"); - try { - builder.setVersion(-0.1); - fail(); - } catch (IllegalArgumentException e) { - assertThat(e).hasMessageThat().isEqualTo("Invalid version: -0.1"); - } + e = assertThrows(IllegalArgumentException.class, () -> builder.setVersion(-0.1)); + assertThat(e).hasMessageThat().isEqualTo("Invalid version: -0.1"); } @Test diff --git a/gson/src/test/java/com/google/gson/GsonTypeAdapterTest.java b/gson/src/test/java/com/google/gson/GsonTypeAdapterTest.java index 6422bacc42..6991c046db 100644 --- a/gson/src/test/java/com/google/gson/GsonTypeAdapterTest.java +++ b/gson/src/test/java/com/google/gson/GsonTypeAdapterTest.java @@ -17,7 +17,7 @@ package com.google.gson; import static com.google.common.truth.Truth.assertThat; -import static org.junit.Assert.fail; +import static org.junit.Assert.assertThrows; import java.lang.reflect.Type; import java.math.BigInteger; @@ -46,29 +46,17 @@ public void setUp() throws Exception { @Test public void testDefaultTypeAdapterThrowsParseException() throws Exception { - try { - gson.fromJson("{\"abc\":123}", BigInteger.class); - fail("Should have thrown a JsonParseException"); - } catch (JsonParseException expected) { - } + assertThrows(JsonParseException.class, () -> gson.fromJson("{\"abc\":123}", BigInteger.class)); } @Test public void testTypeAdapterThrowsException() throws Exception { - try { - gson.toJson(new AtomicLong(0)); - fail("Type Adapter should have thrown an exception"); - } catch (IllegalStateException expected) { - } + assertThrows(IllegalStateException.class, () -> gson.toJson(new AtomicLong(0))); // Verify that serializer is made null-safe, i.e. it is not called for null assertThat(gson.toJson(null, AtomicLong.class)).isEqualTo("null"); - try { - gson.fromJson("123", AtomicLong.class); - fail("Type Adapter should have thrown an exception"); - } catch (JsonParseException expected) { - } + assertThrows(JsonParseException.class, () -> gson.fromJson("123", AtomicLong.class)); // Verify that deserializer is made null-safe, i.e. it is not called for null assertThat(gson.fromJson(JsonNull.INSTANCE, AtomicLong.class)).isNull(); @@ -106,7 +94,7 @@ public JsonElement serialize(AtomicLong src, Type typeOfSrc, JsonSerializationCo public AtomicLong deserialize( JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { - throw new IllegalStateException(); + throw new IllegalStateException("test-exception"); } } diff --git a/gson/src/test/java/com/google/gson/JsonArrayTest.java b/gson/src/test/java/com/google/gson/JsonArrayTest.java index a140814464..e6e60070af 100644 --- a/gson/src/test/java/com/google/gson/JsonArrayTest.java +++ b/gson/src/test/java/com/google/gson/JsonArrayTest.java @@ -17,7 +17,7 @@ package com.google.gson; import static com.google.common.truth.Truth.assertThat; -import static org.junit.Assert.fail; +import static org.junit.Assert.assertThrows; import com.google.common.testing.EqualsTester; import com.google.gson.common.MoreAsserts; @@ -62,11 +62,8 @@ public void testEqualsNonEmptyArray() { @Test public void testRemove() { JsonArray array = new JsonArray(); - try { - array.remove(0); - fail(); - } catch (IndexOutOfBoundsException expected) { - } + assertThrows(IndexOutOfBoundsException.class, () -> array.remove(0)); + JsonPrimitive a = new JsonPrimitive("a"); array.add(a); assertThat(array.remove(a)).isTrue(); @@ -81,11 +78,8 @@ public void testRemove() { @Test public void testSet() { JsonArray array = new JsonArray(); - try { - array.set(0, new JsonPrimitive(1)); - fail(); - } catch (IndexOutOfBoundsException expected) { - } + assertThrows(IndexOutOfBoundsException.class, () -> array.set(0, new JsonPrimitive(1))); + JsonPrimitive a = new JsonPrimitive("a"); array.add(a); @@ -144,77 +138,44 @@ public void testFailedGetArrayValues() { + "\"key3\":\"value3\"," + "\"key4\":\"value4\"" + "}")); - try { - jsonArray.getAsBoolean(); - fail("expected getBoolean to fail"); - } catch (UnsupportedOperationException e) { - assertThat(e).hasMessageThat().isEqualTo("JsonObject"); - } - try { - jsonArray.get(-1); - fail("expected get to fail"); - } catch (IndexOutOfBoundsException e) { - assertThat(e).hasMessageThat().isEqualTo("Index -1 out of bounds for length 1"); - } - try { - jsonArray.getAsString(); - fail("expected getString to fail"); - } catch (UnsupportedOperationException e) { - assertThat(e).hasMessageThat().isEqualTo("JsonObject"); - } + + Exception e = assertThrows(UnsupportedOperationException.class, () -> jsonArray.getAsBoolean()); + assertThat(e).hasMessageThat().isEqualTo("JsonObject"); + + e = assertThrows(IndexOutOfBoundsException.class, () -> jsonArray.get(-1)); + assertThat(e).hasMessageThat().isEqualTo("Index -1 out of bounds for length 1"); + + e = assertThrows(UnsupportedOperationException.class, () -> jsonArray.getAsString()); + assertThat(e).hasMessageThat().isEqualTo("JsonObject"); jsonArray.remove(0); jsonArray.add("hello"); - try { - jsonArray.getAsDouble(); - fail("expected getDouble to fail"); - } catch (NumberFormatException e) { - assertThat(e).hasMessageThat().isEqualTo("For input string: \"hello\""); - } - try { - jsonArray.getAsInt(); - fail("expected getInt to fail"); - } catch (NumberFormatException e) { - assertThat(e).hasMessageThat().isEqualTo("For input string: \"hello\""); - } - try { - jsonArray.get(0).getAsJsonArray(); - fail("expected getJSONArray to fail"); - } catch (IllegalStateException e) { - assertThat(e).hasMessageThat().isEqualTo("Not a JSON Array: \"hello\""); - } - try { - jsonArray.getAsJsonObject(); - fail("expected getJSONObject to fail"); - } catch (IllegalStateException e) { - assertThat(e).hasMessageThat().isEqualTo("Not a JSON Object: [\"hello\"]"); - } - try { - jsonArray.getAsLong(); - fail("expected getLong to fail"); - } catch (NumberFormatException e) { - assertThat(e).hasMessageThat().isEqualTo("For input string: \"hello\""); - } + e = assertThrows(NumberFormatException.class, () -> jsonArray.getAsDouble()); + assertThat(e).hasMessageThat().isEqualTo("For input string: \"hello\""); + + e = assertThrows(NumberFormatException.class, () -> jsonArray.getAsInt()); + assertThat(e).hasMessageThat().isEqualTo("For input string: \"hello\""); + + e = assertThrows(IllegalStateException.class, () -> jsonArray.get(0).getAsJsonArray()); + assertThat(e).hasMessageThat().isEqualTo("Not a JSON Array: \"hello\""); + + e = assertThrows(IllegalStateException.class, () -> jsonArray.getAsJsonObject()); + assertThat(e).hasMessageThat().isEqualTo("Not a JSON Object: [\"hello\"]"); + + e = assertThrows(NumberFormatException.class, () -> jsonArray.getAsLong()); + assertThat(e).hasMessageThat().isEqualTo("For input string: \"hello\""); } @Test public void testGetAs_WrongArraySize() { JsonArray jsonArray = new JsonArray(); - try { - jsonArray.getAsByte(); - fail(); - } catch (IllegalStateException e) { - assertThat(e).hasMessageThat().isEqualTo("Array must have size 1, but has size 0"); - } + var e = assertThrows(IllegalStateException.class, () -> jsonArray.getAsByte()); + assertThat(e).hasMessageThat().isEqualTo("Array must have size 1, but has size 0"); jsonArray.add(true); jsonArray.add(false); - try { - jsonArray.getAsByte(); - fail(); - } catch (IllegalStateException e) { - assertThat(e).hasMessageThat().isEqualTo("Array must have size 1, but has size 2"); - } + e = assertThrows(IllegalStateException.class, () -> jsonArray.getAsByte()); + assertThat(e).hasMessageThat().isEqualTo("Array must have size 1, but has size 2"); } @Test diff --git a/gson/src/test/java/com/google/gson/JsonObjectAsMapTest.java b/gson/src/test/java/com/google/gson/JsonObjectAsMapTest.java index ae8d2ea7dd..0d7a5164e8 100644 --- a/gson/src/test/java/com/google/gson/JsonObjectAsMapTest.java +++ b/gson/src/test/java/com/google/gson/JsonObjectAsMapTest.java @@ -17,7 +17,7 @@ package com.google.gson; import static com.google.common.truth.Truth.assertThat; -import static org.junit.Assert.fail; +import static org.junit.Assert.assertThrows; import com.google.gson.common.MoreAsserts; import java.util.AbstractMap.SimpleEntry; @@ -103,19 +103,11 @@ public void testPut() { assertThat(map.put("b", JsonNull.INSTANCE)).isNull(); assertThat(map.get("b")).isEqualTo(JsonNull.INSTANCE); - try { - map.put(null, new JsonPrimitive(1)); - fail(); - } catch (NullPointerException e) { - assertThat(e).hasMessageThat().isEqualTo("key == null"); - } - - try { - map.put("a", null); - fail(); - } catch (NullPointerException e) { - assertThat(e).hasMessageThat().isEqualTo("value == null"); - } + var e = assertThrows(NullPointerException.class, () -> map.put(null, new JsonPrimitive(1))); + assertThat(e).hasMessageThat().isEqualTo("key == null"); + + e = assertThrows(NullPointerException.class, () -> map.put("a", null)); + assertThat(e).hasMessageThat().isEqualTo("value == null"); } @Test @@ -153,19 +145,19 @@ public void testPutAll() { assertThat(map.get("a")).isEqualTo(new JsonPrimitive(2)); assertThat(map.get("b")).isEqualTo(new JsonPrimitive(3)); - try { - map.putAll(Collections.singletonMap(null, new JsonPrimitive(1))); - fail(); - } catch (NullPointerException e) { - assertThat(e).hasMessageThat().isEqualTo("key == null"); - } - - try { - map.putAll(Collections.singletonMap("a", null)); - fail(); - } catch (NullPointerException e) { - assertThat(e).hasMessageThat().isEqualTo("value == null"); - } + var e = + assertThrows( + NullPointerException.class, + () -> + map.putAll( + Collections.singletonMap(null, new JsonPrimitive(1)))); + assertThat(e).hasMessageThat().isEqualTo("key == null"); + + e = + assertThrows( + NullPointerException.class, + () -> map.putAll(Collections.singletonMap("a", null))); + assertThat(e).hasMessageThat().isEqualTo("value == null"); } @Test @@ -191,11 +183,7 @@ public void testKeySet() { assertThat(keySet).containsExactly("b", "a").inOrder(); // Key set doesn't support insertions - try { - keySet.add("c"); - fail(); - } catch (UnsupportedOperationException e) { - } + assertThrows(UnsupportedOperationException.class, () -> keySet.add("c")); assertThat(keySet.remove("a")).isTrue(); assertThat(map.keySet()).isEqualTo(Collections.singleton("b")); @@ -214,11 +202,7 @@ public void testValues() { assertThat(values).containsExactly(new JsonPrimitive(2), new JsonPrimitive(1)).inOrder(); // Values collection doesn't support insertions - try { - values.add(new JsonPrimitive(3)); - fail(); - } catch (UnsupportedOperationException e) { - } + assertThrows(UnsupportedOperationException.class, () -> values.add(new JsonPrimitive(3))); assertThat(values.remove(new JsonPrimitive(2))).isTrue(); assertThat(new ArrayList<>(map.values())) @@ -243,11 +227,9 @@ public void testEntrySet() { // Should contain entries in same order assertThat(new ArrayList<>(entrySet)).isEqualTo(expectedEntrySet); - try { - entrySet.add(new SimpleEntry("c", new JsonPrimitive(3))); - fail(); - } catch (UnsupportedOperationException e) { - } + assertThrows( + UnsupportedOperationException.class, + () -> entrySet.add(new SimpleEntry("c", new JsonPrimitive(3)))); assertThat(entrySet.remove(new SimpleEntry<>("a", new JsonPrimitive(1)))).isTrue(); assertThat(map.entrySet()) @@ -266,12 +248,8 @@ public void testEntrySet() { assertThat(o.entrySet()) .isEqualTo(Collections.singleton(new SimpleEntry<>("b", new JsonPrimitive(3)))); - try { - entry.setValue(null); - fail(); - } catch (NullPointerException e) { - assertThat(e).hasMessageThat().isEqualTo("value == null"); - } + var e = assertThrows(NullPointerException.class, () -> entry.setValue(null)); + assertThat(e).hasMessageThat().isEqualTo("value == null"); } @Test diff --git a/gson/src/test/java/com/google/gson/JsonObjectTest.java b/gson/src/test/java/com/google/gson/JsonObjectTest.java index da6931c984..a728fda3be 100644 --- a/gson/src/test/java/com/google/gson/JsonObjectTest.java +++ b/gson/src/test/java/com/google/gson/JsonObjectTest.java @@ -17,7 +17,7 @@ package com.google.gson; import static com.google.common.truth.Truth.assertThat; -import static org.junit.Assert.fail; +import static org.junit.Assert.assertThrows; import com.google.common.testing.EqualsTester; import com.google.gson.common.MoreAsserts; @@ -75,14 +75,12 @@ public void testAddingNullPropertyValue() { @Test public void testAddingNullOrEmptyPropertyName() { JsonObject jsonObj = new JsonObject(); - try { - jsonObj.add(null, JsonNull.INSTANCE); - fail("Should not allow null property names."); - } catch (NullPointerException expected) { - } + // Should not allow null property names + assertThrows(NullPointerException.class, () -> jsonObj.add(null, JsonNull.INSTANCE)); jsonObj.add("", JsonNull.INSTANCE); jsonObj.add(" \t", JsonNull.INSTANCE); + assertThat(jsonObj.keySet()).containsExactly("", " \t"); } @Test @@ -308,15 +306,11 @@ public void testEntrySet() { assertThat(new ArrayList<>(o.entrySet())).isEqualTo(expectedEntriesList); Entry entry = o.entrySet().iterator().next(); - try { - // null value is not permitted, only JsonNull is supported - // This intentionally deviates from the behavior of the other JsonObject methods which - // implicitly convert null -> JsonNull, to match more closely the contract of Map.Entry - entry.setValue(null); - fail(); - } catch (NullPointerException e) { - assertThat(e).hasMessageThat().isEqualTo("value == null"); - } + // null value is not permitted, only JsonNull is supported + // This intentionally deviates from the behavior of the other JsonObject methods which + // implicitly convert null -> JsonNull, to match more closely the contract of Map.Entry + var e = assertThrows(NullPointerException.class, () -> entry.setValue(null)); + assertThat(e).hasMessageThat().isEqualTo("value == null"); assertThat(entry.getValue()).isNotNull(); o.addProperty("key1", 1); diff --git a/gson/src/test/java/com/google/gson/JsonPrimitiveTest.java b/gson/src/test/java/com/google/gson/JsonPrimitiveTest.java index be1e122544..be73c315ad 100644 --- a/gson/src/test/java/com/google/gson/JsonPrimitiveTest.java +++ b/gson/src/test/java/com/google/gson/JsonPrimitiveTest.java @@ -18,7 +18,7 @@ import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertWithMessage; -import static org.junit.Assert.fail; +import static org.junit.Assert.assertThrows; import com.google.gson.common.MoreAsserts; import java.math.BigDecimal; @@ -35,26 +35,10 @@ public class JsonPrimitiveTest { @SuppressWarnings("unused") @Test public void testNulls() { - try { - new JsonPrimitive((Boolean) null); - fail(); - } catch (NullPointerException ignored) { - } - try { - new JsonPrimitive((Number) null); - fail(); - } catch (NullPointerException ignored) { - } - try { - new JsonPrimitive((String) null); - fail(); - } catch (NullPointerException ignored) { - } - try { - new JsonPrimitive((Character) null); - fail(); - } catch (NullPointerException ignored) { - } + assertThrows(NullPointerException.class, () -> new JsonPrimitive((Boolean) null)); + assertThrows(NullPointerException.class, () -> new JsonPrimitive((Number) null)); + assertThrows(NullPointerException.class, () -> new JsonPrimitive((String) null)); + assertThrows(NullPointerException.class, () -> new JsonPrimitive((Character) null)); } @Test @@ -107,12 +91,8 @@ public void testParsingStringAsNumber() { @Test public void testAsNumber_Boolean() { JsonPrimitive json = new JsonPrimitive(true); - try { - json.getAsNumber(); - fail(); - } catch (UnsupportedOperationException e) { - assertThat(e).hasMessageThat().isEqualTo("Primitive is neither a number nor a string"); - } + var e = assertThrows(UnsupportedOperationException.class, () -> json.getAsNumber()); + assertThat(e).hasMessageThat().isEqualTo("Primitive is neither a number nor a string"); } @SuppressWarnings("deprecation") @@ -131,14 +111,11 @@ public void testStringsAndChar() { json = new JsonPrimitive(true); assertThat(json.getAsString()).isEqualTo("true"); - json = new JsonPrimitive(""); - assertThat(json.getAsString()).isEqualTo(""); - try { - json.getAsCharacter(); - fail(); - } catch (UnsupportedOperationException e) { - assertThat(e).hasMessageThat().isEqualTo("String value is empty"); - } + JsonPrimitive emptyString = new JsonPrimitive(""); + assertThat(emptyString.getAsString()).isEqualTo(""); + + var e = assertThrows(UnsupportedOperationException.class, () -> emptyString.getAsCharacter()); + assertThat(e).hasMessageThat().isEqualTo("String value is empty"); } @Test @@ -148,11 +125,8 @@ public void testExponential() { assertThat(json.getAsBigDecimal()).isEqualTo(new BigDecimal("1E+7")); assertThat(json.getAsDouble()).isEqualTo(1E+7); - try { - json.getAsInt(); - fail("Integers can not handle exponents like this."); - } catch (NumberFormatException expected) { - } + // Integers can not handle exponents like this + assertThrows(NumberFormatException.class, () -> json.getAsInt()); } @Test diff --git a/gson/src/test/java/com/google/gson/MixedStreamTest.java b/gson/src/test/java/com/google/gson/MixedStreamTest.java index 23c887d12d..2dd53bbf46 100644 --- a/gson/src/test/java/com/google/gson/MixedStreamTest.java +++ b/gson/src/test/java/com/google/gson/MixedStreamTest.java @@ -17,7 +17,7 @@ package com.google.gson; import static com.google.common.truth.Truth.assertThat; -import static org.junit.Assert.fail; +import static org.junit.Assert.assertThrows; import com.google.gson.reflect.TypeToken; import com.google.gson.stream.JsonReader; @@ -98,7 +98,7 @@ public void testReaderDoesNotMutateState() throws IOException { @SuppressWarnings("deprecation") // for JsonWriter.setLenient @Test - public void testWriteDoesNotMutateState() throws IOException { + public void testWriterDoesNotMutateState() throws IOException { Gson gson = new Gson(); JsonWriter jsonWriter = new JsonWriter(new StringWriter()); jsonWriter.beginArray(); @@ -122,11 +122,7 @@ public void testReadInvalidState() throws IOException { JsonReader jsonReader = new JsonReader(new StringReader(CARS_JSON)); jsonReader.beginArray(); jsonReader.beginObject(); - try { - gson.fromJson(jsonReader, String.class); - fail(); - } catch (JsonParseException expected) { - } + assertThrows(JsonParseException.class, () -> gson.fromJson(jsonReader, String.class)); } @Test @@ -134,11 +130,11 @@ public void testReadClosed() throws IOException { Gson gson = new Gson(); JsonReader jsonReader = new JsonReader(new StringReader(CARS_JSON)); jsonReader.close(); - try { - gson.fromJson(jsonReader, new TypeToken>() {}.getType()); - fail(); - } catch (JsonParseException expected) { - } + var e = + assertThrows( + JsonParseException.class, + () -> gson.fromJson(jsonReader, new TypeToken>() {}.getType())); + assertThat(e).hasCauseThat().hasMessageThat().isEqualTo("JsonReader is closed"); } @Test @@ -146,11 +142,10 @@ public void testWriteInvalidState() throws IOException { Gson gson = new Gson(); JsonWriter jsonWriter = new JsonWriter(new StringWriter()); jsonWriter.beginObject(); - try { - gson.toJson(BLUE_MUSTANG, Car.class, jsonWriter); - fail(); - } catch (IllegalStateException expected) { - } + var e = + assertThrows( + IllegalStateException.class, () -> gson.toJson(BLUE_MUSTANG, Car.class, jsonWriter)); + assertThat(e).hasMessageThat().isEqualTo("Nesting problem."); } @Test @@ -160,21 +155,18 @@ public void testWriteClosed() throws IOException { jsonWriter.beginArray(); jsonWriter.endArray(); jsonWriter.close(); - try { - gson.toJson(BLUE_MUSTANG, Car.class, jsonWriter); - fail(); - } catch (IllegalStateException expected) { - } + var e = + assertThrows( + IllegalStateException.class, () -> gson.toJson(BLUE_MUSTANG, Car.class, jsonWriter)); + assertThat(e).hasMessageThat().isEqualTo("JsonWriter is closed."); } @Test public void testWriteNulls() { Gson gson = new Gson(); - try { - gson.toJson(new JsonPrimitive("hello"), (JsonWriter) null); - fail(); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, + () -> gson.toJson(new JsonPrimitive("hello"), (JsonWriter) null)); StringWriter stringWriter = new StringWriter(); gson.toJson(null, new JsonWriter(stringWriter)); @@ -184,16 +176,10 @@ public void testWriteNulls() { @Test public void testReadNulls() { Gson gson = new Gson(); - try { - gson.fromJson((JsonReader) null, Integer.class); - fail(); - } catch (NullPointerException expected) { - } - try { - gson.fromJson(new JsonReader(new StringReader("true")), (Type) null); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> gson.fromJson((JsonReader) null, Integer.class)); + assertThrows( + NullPointerException.class, + () -> gson.fromJson(new JsonReader(new StringReader("true")), (Type) null)); } @Test @@ -232,11 +218,15 @@ public void testWriteLenient() { .toJson(doubles, type, jsonWriter); assertThat(writer.toString()).isEqualTo("[NaN,-Infinity,Infinity,-0.0,0.5,0.0]"); - try { - new Gson().toJson(doubles, type, new JsonWriter(new StringWriter())); - fail(); - } catch (IllegalArgumentException expected) { - } + var e = + assertThrows( + IllegalArgumentException.class, + () -> new Gson().toJson(doubles, type, new JsonWriter(new StringWriter()))); + assertThat(e) + .hasMessageThat() + .isEqualTo( + "NaN is not a valid double value as per JSON specification. To override this behavior," + + " use GsonBuilder.serializeSpecialFloatingPointValues() method."); } static final class Car { diff --git a/gson/src/test/java/com/google/gson/functional/ArrayTest.java b/gson/src/test/java/com/google/gson/functional/ArrayTest.java index a88ad9f471..b8a4e3a069 100644 --- a/gson/src/test/java/com/google/gson/functional/ArrayTest.java +++ b/gson/src/test/java/com/google/gson/functional/ArrayTest.java @@ -17,7 +17,7 @@ package com.google.gson.functional; import static com.google.common.truth.Truth.assertThat; -import static org.junit.Assert.fail; +import static org.junit.Assert.assertThrows; import com.google.gson.Gson; import com.google.gson.GsonBuilder; @@ -62,11 +62,9 @@ public void testTopLevelArrayOfIntsDeserialization() { @Test public void testInvalidArrayDeserialization() { String json = "[1, 2 3, 4, 5]"; - try { - gson.fromJson(json, int[].class); - fail("Gson should not deserialize array elements with missing ,"); - } catch (JsonParseException expected) { - } + // Gson should not deserialize array elements with missing ',' + var e = assertThrows(JsonParseException.class, () -> gson.fromJson(json, int[].class)); + assertThat(e).hasCauseThat().hasMessageThat().startsWith("Unterminated array"); } @Test diff --git a/gson/src/test/java/com/google/gson/functional/CircularReferenceTest.java b/gson/src/test/java/com/google/gson/functional/CircularReferenceTest.java index 3cd110f736..847284f6b1 100644 --- a/gson/src/test/java/com/google/gson/functional/CircularReferenceTest.java +++ b/gson/src/test/java/com/google/gson/functional/CircularReferenceTest.java @@ -16,7 +16,7 @@ package com.google.gson.functional; import static com.google.common.truth.Truth.assertThat; -import static org.junit.Assert.fail; +import static org.junit.Assert.assertThrows; import com.google.gson.Gson; import com.google.gson.GsonBuilder; @@ -51,11 +51,8 @@ public void testCircularSerialization() { ContainsReferenceToSelfType b = new ContainsReferenceToSelfType(); a.children.add(b); b.children.add(a); - try { - gson.toJson(a); - fail("Circular types should not get printed!"); - } catch (StackOverflowError expected) { - } + // Circular types should not get printed + assertThrows(StackOverflowError.class, () -> gson.toJson(a)); } @Test @@ -72,11 +69,8 @@ public void testSelfReferenceArrayFieldSerialization() { ClassWithSelfReferenceArray objA = new ClassWithSelfReferenceArray(); objA.children = new ClassWithSelfReferenceArray[] {objA}; - try { - gson.toJson(objA); - fail("Circular reference to self can not be serialized!"); - } catch (StackOverflowError expected) { - } + // Circular reference to self can not be serialized + assertThrows(StackOverflowError.class, () -> gson.toJson(objA)); } @Test @@ -100,11 +94,9 @@ public JsonElement serialize( } }) .create(); - try { - gson.toJson(obj); - fail("Circular reference to self can not be serialized!"); - } catch (StackOverflowError expected) { - } + + // Circular reference to self can not be serialized + assertThrows(StackOverflowError.class, () -> gson.toJson(obj)); } @Test diff --git a/gson/src/test/java/com/google/gson/functional/EnumWithObfuscatedTest.java b/gson/src/test/java/com/google/gson/functional/EnumWithObfuscatedTest.java index c50c482fbd..a17b6c28c9 100644 --- a/gson/src/test/java/com/google/gson/functional/EnumWithObfuscatedTest.java +++ b/gson/src/test/java/com/google/gson/functional/EnumWithObfuscatedTest.java @@ -17,7 +17,7 @@ package com.google.gson.functional; import static com.google.common.truth.Truth.assertThat; -import static org.junit.Assert.fail; +import static org.junit.Assert.assertThrows; import com.google.gson.Gson; import com.google.gson.annotations.SerializedName; @@ -48,11 +48,10 @@ public enum Gender { @Test public void testEnumClassWithObfuscated() { for (Gender enumConstant : Gender.class.getEnumConstants()) { - try { - Gender.class.getField(enumConstant.name()); - fail("Enum is not obfuscated"); - } catch (NoSuchFieldException ignore) { - } + assertThrows( + "Enum is not obfuscated", + NoSuchFieldException.class, + () -> Gender.class.getField(enumConstant.name())); } assertThat(gson.fromJson("\"MAIL\"", Gender.class)).isEqualTo(Gender.MALE); diff --git a/gson/src/test/java/com/google/gson/functional/FormattingStyleTest.java b/gson/src/test/java/com/google/gson/functional/FormattingStyleTest.java index 2c4d551963..fa07a3c9fd 100644 --- a/gson/src/test/java/com/google/gson/functional/FormattingStyleTest.java +++ b/gson/src/test/java/com/google/gson/functional/FormattingStyleTest.java @@ -16,7 +16,7 @@ package com.google.gson.functional; import static com.google.common.truth.Truth.assertThat; -import static org.junit.Assert.fail; +import static org.junit.Assert.assertThrows; import com.google.gson.FormattingStyle; import com.google.gson.Gson; @@ -182,33 +182,25 @@ public void testPrettyToCompact() { @Test public void testStyleValidations() { - try { - // TBD if we want to accept \u2028 and \u2029. For now we don't because JSON specification - // does not consider them to be newlines - FormattingStyle.PRETTY.withNewline("\u2028"); - fail("Gson should not accept anything but \\r and \\n for newline"); - } catch (IllegalArgumentException expected) { - assertThat(expected) - .hasMessageThat() - .isEqualTo("Only combinations of \\n and \\r are allowed in newline."); - } - - try { - FormattingStyle.PRETTY.withNewline("NL"); - fail("Gson should not accept anything but \\r and \\n for newline"); - } catch (IllegalArgumentException expected) { - assertThat(expected) - .hasMessageThat() - .isEqualTo("Only combinations of \\n and \\r are allowed in newline."); - } - - try { - FormattingStyle.PRETTY.withIndent("\f"); - fail("Gson should not accept anything but space and tab for indent"); - } catch (IllegalArgumentException expected) { - assertThat(expected) - .hasMessageThat() - .isEqualTo("Only combinations of spaces and tabs are allowed in indent."); - } + // TBD if we want to accept \u2028 and \u2029. For now we don't because JSON specification + // does not consider them to be newlines + var e = + assertThrows( + IllegalArgumentException.class, () -> FormattingStyle.PRETTY.withNewline("\u2028")); + assertThat(e) + .hasMessageThat() + .isEqualTo("Only combinations of \\n and \\r are allowed in newline."); + + e = + assertThrows( + IllegalArgumentException.class, () -> FormattingStyle.PRETTY.withNewline("NL")); + assertThat(e) + .hasMessageThat() + .isEqualTo("Only combinations of \\n and \\r are allowed in newline."); + + e = assertThrows(IllegalArgumentException.class, () -> FormattingStyle.PRETTY.withIndent("\f")); + assertThat(e) + .hasMessageThat() + .isEqualTo("Only combinations of spaces and tabs are allowed in indent."); } } diff --git a/gson/src/test/java/com/google/gson/functional/Java17RecordTest.java b/gson/src/test/java/com/google/gson/functional/Java17RecordTest.java index 437fe8124e..87e1a4bb4b 100644 --- a/gson/src/test/java/com/google/gson/functional/Java17RecordTest.java +++ b/gson/src/test/java/com/google/gson/functional/Java17RecordTest.java @@ -17,7 +17,6 @@ import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.assertThrows; -import static org.junit.Assert.fail; import com.google.gson.ExclusionStrategy; import com.google.gson.FieldAttributes; @@ -156,12 +155,8 @@ record LocalRecord(String s) { } } - try { - gson.fromJson("{\"s\":\"value\"}", LocalRecord.class); - fail(); - } // TODO: Adjust this once Gson throws more specific exception type - catch (RuntimeException e) { + var e = assertThrows(RuntimeException.class, () -> gson.fromJson("{\"s\":\"value\"}", LocalRecord.class)); assertThat(e) .hasMessageThat() .isEqualTo( @@ -169,7 +164,6 @@ record LocalRecord(String s) { + LocalRecord.class.getName() + "(String)' with args [value]"); assertThat(e).hasCauseThat().isSameInstanceAs(LocalRecord.thrownException); - } } @Test @@ -197,15 +191,11 @@ public String s() { } } - try { - gson.toJson(new LocalRecord("a")); - fail(); - } catch (JsonIOException e) { + 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); - } } /** Tests behavior for a record without components */ diff --git a/gson/src/test/java/com/google/gson/functional/JsonAdapterAnnotationOnClassesTest.java b/gson/src/test/java/com/google/gson/functional/JsonAdapterAnnotationOnClassesTest.java index 3a765f1352..bb155add64 100644 --- a/gson/src/test/java/com/google/gson/functional/JsonAdapterAnnotationOnClassesTest.java +++ b/gson/src/test/java/com/google/gson/functional/JsonAdapterAnnotationOnClassesTest.java @@ -17,7 +17,7 @@ package com.google.gson.functional; import static com.google.common.truth.Truth.assertThat; -import static org.junit.Assert.fail; +import static org.junit.Assert.assertThrows; import com.google.common.base.Splitter; import com.google.gson.Gson; @@ -131,11 +131,9 @@ public A deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext @Test public void testIncorrectTypeAdapterFails() { - try { - String json = new Gson().toJson(new ClassWithIncorrectJsonAdapter("bar")); - fail(json); - } catch (ClassCastException expected) { - } + Gson gson = new Gson(); + ClassWithIncorrectJsonAdapter obj = new ClassWithIncorrectJsonAdapter("bar"); + assertThrows(ClassCastException.class, () -> gson.toJson(obj)); } @Test @@ -373,11 +371,9 @@ public Foo read(JsonReader in) throws IOException { @Test public void testIncorrectJsonAdapterType() { - try { - new Gson().toJson(new D()); - fail(); - } catch (IllegalArgumentException expected) { - } + Gson gson = new Gson(); + D obj = new D(); + assertThrows(IllegalArgumentException.class, () -> gson.toJson(obj)); } @JsonAdapter(Integer.class) diff --git a/gson/src/test/java/com/google/gson/functional/JsonParserTest.java b/gson/src/test/java/com/google/gson/functional/JsonParserTest.java index 21e16e826d..8340175f15 100644 --- a/gson/src/test/java/com/google/gson/functional/JsonParserTest.java +++ b/gson/src/test/java/com/google/gson/functional/JsonParserTest.java @@ -17,7 +17,7 @@ package com.google.gson.functional; import static com.google.common.truth.Truth.assertThat; -import static org.junit.Assert.fail; +import static org.junit.Assert.assertThrows; import com.google.gson.Gson; import com.google.gson.JsonArray; @@ -53,11 +53,7 @@ public void setUp() throws Exception { @Test public void testParseInvalidJson() { - try { - gson.fromJson("[[]", Object[].class); - fail(); - } catch (JsonSyntaxException expected) { - } + assertThrows(JsonSyntaxException.class, () -> gson.fromJson("[[]", Object[].class)); } @Test @@ -77,11 +73,8 @@ public void testBadTypeForDeserializingCustomTree() { obj.addProperty("intValue", 11); JsonArray array = new JsonArray(); array.add(obj); - try { - gson.fromJson(array, BagOfPrimitives.class); - fail("BagOfPrimitives is not an array"); - } catch (JsonParseException expected) { - } + // BagOfPrimitives is not an array + assertThrows(JsonParseException.class, () -> gson.fromJson(array, BagOfPrimitives.class)); } @Test @@ -93,11 +86,8 @@ public void testBadFieldTypeForCustomDeserializerCustomTree() { obj.addProperty("intValue", 11); obj.add("longValue", array); - try { - gson.fromJson(obj, BagOfPrimitives.class); - fail("BagOfPrimitives is not an array"); - } catch (JsonParseException expected) { - } + // `longValue` should not be an array + assertThrows(JsonParseException.class, () -> gson.fromJson(obj, BagOfPrimitives.class)); } @Test @@ -112,11 +102,8 @@ public void testBadFieldTypeForDeserializingCustomTree() { obj.add("primitive1", primitive1); obj.add("primitive2", array); - try { - gson.fromJson(obj, Nested.class); - fail("Nested has field BagOfPrimitives which is not an array"); - } catch (JsonParseException expected) { - } + // Nested has field BagOfPrimitives which is not an array + assertThrows(JsonParseException.class, () -> gson.fromJson(obj, Nested.class)); } @Test @@ -144,10 +131,6 @@ public void testExtraCommasInArrays() { @Test public void testExtraCommasInMaps() { Type type = new TypeToken>() {}.getType(); - try { - gson.fromJson("{a:b,}", type); - fail(); - } catch (JsonSyntaxException expected) { - } + assertThrows(JsonParseException.class, () -> gson.fromJson("{a:b,}", type)); } } diff --git a/gson/src/test/java/com/google/gson/functional/JsonTreeTest.java b/gson/src/test/java/com/google/gson/functional/JsonTreeTest.java index 4a00f399d0..82f8aae88c 100644 --- a/gson/src/test/java/com/google/gson/functional/JsonTreeTest.java +++ b/gson/src/test/java/com/google/gson/functional/JsonTreeTest.java @@ -17,7 +17,6 @@ package com.google.gson.functional; import static com.google.common.truth.Truth.assertThat; -import static org.junit.Assert.fail; import com.google.gson.Gson; import com.google.gson.JsonElement; @@ -98,7 +97,7 @@ private static void assertContains(JsonObject json, JsonPrimitive child) { } } } - fail(); + throw new AssertionError("Does not contain " + child); } private static class SubTypeOfBagOfPrimitives extends BagOfPrimitives { diff --git a/gson/src/test/java/com/google/gson/functional/MapAsArrayTypeAdapterTest.java b/gson/src/test/java/com/google/gson/functional/MapAsArrayTypeAdapterTest.java index 7009ce6cbf..61944bc4ed 100644 --- a/gson/src/test/java/com/google/gson/functional/MapAsArrayTypeAdapterTest.java +++ b/gson/src/test/java/com/google/gson/functional/MapAsArrayTypeAdapterTest.java @@ -17,7 +17,7 @@ package com.google.gson.functional; import static com.google.common.truth.Truth.assertThat; -import static org.junit.Assert.fail; +import static org.junit.Assert.assertThrows; import com.google.gson.Gson; import com.google.gson.GsonBuilder; @@ -58,18 +58,15 @@ public void testSerializeComplexMapWithTypeAdapter() { } @Test - @Ignore + @Ignore("we no longer hash keys at serialization time") public void testTwoTypesCollapseToOneSerialize() { Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create(); Map original = new LinkedHashMap<>(); original.put(1.0D, "a"); original.put(1.0F, "b"); - try { - gson.toJson(original, new TypeToken>() {}.getType()); - fail(); // we no longer hash keys at serialization time - } catch (JsonSyntaxException expected) { - } + Type type = new TypeToken>() {}.getType(); + assertThrows(JsonSyntaxException.class, () -> gson.toJson(original, type)); } @Test @@ -77,11 +74,9 @@ public void testTwoTypesCollapseToOneDeserialize() { Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create(); String s = "[[\"1.00\",\"a\"],[\"1.0\",\"b\"]]"; - try { - gson.fromJson(s, new TypeToken>() {}.getType()); - fail(); - } catch (JsonSyntaxException expected) { - } + Type type = new TypeToken>() {}.getType(); + var e = assertThrows(JsonSyntaxException.class, () -> gson.fromJson(s, type)); + assertThat(e).hasMessageThat().isEqualTo("duplicate key: 1.0"); } @Test diff --git a/gson/src/test/java/com/google/gson/functional/MapTest.java b/gson/src/test/java/com/google/gson/functional/MapTest.java index 0bd11c4c7a..0bb9969ede 100644 --- a/gson/src/test/java/com/google/gson/functional/MapTest.java +++ b/gson/src/test/java/com/google/gson/functional/MapTest.java @@ -17,7 +17,7 @@ package com.google.gson.functional; import static com.google.common.truth.Truth.assertThat; -import static org.junit.Assert.fail; +import static org.junit.Assert.assertThrows; import com.google.gson.Gson; import com.google.gson.GsonBuilder; @@ -576,11 +576,12 @@ public void testComplexKeysSerialization() { @Test public void testComplexKeysDeserialization() { String json = "{'2,3':'a','5,7':'b'}"; - try { - gson.fromJson(json, new TypeToken>() {}.getType()); - fail(); - } catch (JsonParseException expected) { - } + Type type = new TypeToken>() {}.getType(); + var e = assertThrows(JsonParseException.class, () -> gson.fromJson(json, type)); + assertThat(e) + .hasCauseThat() + .hasMessageThat() + .startsWith("Expected BEGIN_OBJECT but was STRING at line 1 column 3 path $"); } @Test @@ -612,11 +613,9 @@ public void testBooleanKeyDeserialization() { @Test public void testMapDeserializationWithDuplicateKeys() { - try { - gson.fromJson("{'a':1,'a':2}", new TypeToken>() {}.getType()); - fail(); - } catch (JsonSyntaxException expected) { - } + Type type = new TypeToken>() {}.getType(); + var e = assertThrows(JsonSyntaxException.class, () -> gson.fromJson("{'a':1,'a':2}", type)); + assertThat(e).hasMessageThat().isEqualTo("duplicate key: a"); } @Test diff --git a/gson/src/test/java/com/google/gson/functional/NamingPolicyTest.java b/gson/src/test/java/com/google/gson/functional/NamingPolicyTest.java index 8a1d91481e..70780bf7a0 100644 --- a/gson/src/test/java/com/google/gson/functional/NamingPolicyTest.java +++ b/gson/src/test/java/com/google/gson/functional/NamingPolicyTest.java @@ -16,7 +16,7 @@ package com.google.gson.functional; import static com.google.common.truth.Truth.assertThat; -import static org.junit.Assert.fail; +import static org.junit.Assert.assertThrows; import com.google.gson.FieldNamingPolicy; import com.google.gson.FieldNamingStrategy; @@ -142,20 +142,16 @@ public void testGsonWithSerializedNameFieldNamingPolicyDeserialization() { @Test public void testGsonDuplicateNameUsingSerializedNameFieldNamingPolicySerialization() { Gson gson = builder.create(); - try { - ClassWithDuplicateFields target = new ClassWithDuplicateFields(10); - gson.toJson(target); - fail(); - } catch (IllegalArgumentException expected) { - 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\n" - + "See https://github.com/google/gson/blob/main/Troubleshooting.md#duplicate-fields"); - } + ClassWithDuplicateFields target = new ClassWithDuplicateFields(10); + var e = assertThrows(IllegalArgumentException.class, () -> gson.toJson(target)); + assertThat(e) + .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\n" + + "See https://github.com/google/gson/blob/main/Troubleshooting.md#duplicate-fields"); } @Test @@ -171,19 +167,16 @@ public String translateName(Field f) { }) .create(); - try { - gson.toJson(new ClassWithTwoFields()); - fail(); - } catch (IllegalArgumentException expected) { - assertThat(expected) - .hasMessageThat() - .isEqualTo( - "Class com.google.gson.functional.NamingPolicyTest$ClassWithTwoFields declares" - + " multiple JSON fields named 'x'; conflict is caused by fields" - + " com.google.gson.functional.NamingPolicyTest$ClassWithTwoFields#a and" - + " com.google.gson.functional.NamingPolicyTest$ClassWithTwoFields#b\n" - + "See https://github.com/google/gson/blob/main/Troubleshooting.md#duplicate-fields"); - } + var e = + assertThrows(IllegalArgumentException.class, () -> gson.toJson(new ClassWithTwoFields())); + assertThat(e) + .hasMessageThat() + .isEqualTo( + "Class com.google.gson.functional.NamingPolicyTest$ClassWithTwoFields declares multiple" + + " JSON fields named 'x'; conflict is caused by fields" + + " com.google.gson.functional.NamingPolicyTest$ClassWithTwoFields#a and" + + " com.google.gson.functional.NamingPolicyTest$ClassWithTwoFields#b\n" + + "See https://github.com/google/gson/blob/main/Troubleshooting.md#duplicate-fields"); } @Test diff --git a/gson/src/test/java/com/google/gson/functional/ObjectTest.java b/gson/src/test/java/com/google/gson/functional/ObjectTest.java index d0f7e38d76..b7e50610e6 100644 --- a/gson/src/test/java/com/google/gson/functional/ObjectTest.java +++ b/gson/src/test/java/com/google/gson/functional/ObjectTest.java @@ -17,7 +17,7 @@ package com.google.gson.functional; import static com.google.common.truth.Truth.assertThat; -import static org.junit.Assert.fail; +import static org.junit.Assert.assertThrows; import com.google.gson.ExclusionStrategy; import com.google.gson.FieldAttributes; @@ -183,12 +183,8 @@ public void testClassWithDuplicateFields() { + " com.google.gson.functional.ObjectTest$Superclass2#s\n" + "See https://github.com/google/gson/blob/main/Troubleshooting.md#duplicate-fields"; - try { - gson.getAdapter(Subclass.class); - fail(); - } catch (IllegalArgumentException e) { - assertThat(e).hasMessageThat().isEqualTo(expectedMessage); - } + var e = assertThrows(IllegalArgumentException.class, () -> gson.getAdapter(Subclass.class)); + assertThat(e).hasMessageThat().isEqualTo(expectedMessage); // Detection should also work properly when duplicate fields exist only for serialization Gson gson = @@ -208,12 +204,8 @@ public boolean shouldSkipClass(Class clazz) { }) .create(); - try { - gson.getAdapter(Subclass.class); - fail(); - } catch (IllegalArgumentException e) { - assertThat(e).hasMessageThat().isEqualTo(expectedMessage); - } + e = assertThrows(IllegalArgumentException.class, () -> gson.getAdapter(Subclass.class)); + assertThat(e).hasMessageThat().isEqualTo(expectedMessage); } @Test @@ -248,11 +240,8 @@ public void testEmptyStringDeserialization() { @Test public void testTruncatedDeserialization() { - try { - gson.fromJson("[\"a\", \"b\",", new TypeToken>() {}.getType()); - fail(); - } catch (JsonParseException expected) { - } + Type type = new TypeToken>() {}.getType(); + assertThrows(JsonParseException.class, () -> gson.fromJson("[\"a\", \"b\",", type)); } @Test @@ -724,16 +713,15 @@ public void testStaticFieldDeserialization() { ClassWithStaticField.s = oldValue; } - try { - gson.fromJson("{\"s\":\"custom\"}", ClassWithStaticFinalField.class); - fail(); - } catch (JsonIOException e) { - assertThat(e) - .hasMessageThat() - .isEqualTo( - "Cannot set value of 'static final' field" - + " 'com.google.gson.functional.ObjectTest$ClassWithStaticFinalField#s'"); - } + var e = + assertThrows( + JsonIOException.class, + () -> gson.fromJson("{\"s\":\"custom\"}", ClassWithStaticFinalField.class)); + assertThat(e) + .hasMessageThat() + .isEqualTo( + "Cannot set value of 'static final' field" + + " 'com.google.gson.functional.ObjectTest$ClassWithStaticFinalField#s'"); } @SuppressWarnings({"PrivateConstructorForUtilityClass", "NonFinalStaticField"}) @@ -748,20 +736,17 @@ static class ClassWithStaticFinalField { @Test public void testThrowingDefaultConstructor() { - try { - gson.fromJson("{}", ClassWithThrowingConstructor.class); - fail(); - } // TODO: Adjust this once Gson throws more specific exception type - catch (RuntimeException e) { - assertThat(e) - .hasMessageThat() - .isEqualTo( - "Failed to invoke constructor" - + " 'com.google.gson.functional.ObjectTest$ClassWithThrowingConstructor()' with" - + " no args"); - assertThat(e).hasCauseThat().isSameInstanceAs(ClassWithThrowingConstructor.thrownException); - } + var e = + assertThrows( + RuntimeException.class, () -> gson.fromJson("{}", ClassWithThrowingConstructor.class)); + assertThat(e) + .hasMessageThat() + .isEqualTo( + "Failed to invoke constructor" + + " 'com.google.gson.functional.ObjectTest$ClassWithThrowingConstructor()' with" + + " no args"); + assertThat(e).hasCauseThat().isSameInstanceAs(ClassWithThrowingConstructor.thrownException); } @SuppressWarnings("StaticAssignmentOfThrowable") diff --git a/gson/src/test/java/com/google/gson/functional/PrimitiveTest.java b/gson/src/test/java/com/google/gson/functional/PrimitiveTest.java index 2c51f09750..8b8842d344 100644 --- a/gson/src/test/java/com/google/gson/functional/PrimitiveTest.java +++ b/gson/src/test/java/com/google/gson/functional/PrimitiveTest.java @@ -18,7 +18,6 @@ import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.assertThrows; -import static org.junit.Assert.fail; import com.google.gson.Gson; import com.google.gson.GsonBuilder; @@ -494,11 +493,8 @@ public void testSmallValueForBigIntegerDeserialization() { @Test public void testBadValueForBigIntegerDeserialization() { - try { - gson.fromJson("15.099", BigInteger.class); - fail("BigInteger can not be decimal values."); - } catch (JsonSyntaxException expected) { - } + // BigInteger can not be decimal values + assertThrows(JsonSyntaxException.class, () -> gson.fromJson("15.099", BigInteger.class)); } @Test @@ -532,159 +528,167 @@ private static String extractElementFromArray(String json) { @Test public void testDoubleNaNSerializationNotSupportedByDefault() { - try { - double nan = Double.NaN; - gson.toJson(nan); - fail("Gson should not accept NaN for serialization"); - } catch (IllegalArgumentException expected) { - } - try { - gson.toJson(Double.NaN); - fail("Gson should not accept NaN for serialization"); - } catch (IllegalArgumentException expected) { - } + var e = assertThrows(IllegalArgumentException.class, () -> gson.toJson(Double.NaN)); + assertThat(e) + .hasMessageThat() + .isEqualTo( + "NaN is not a valid double value as per JSON specification. To override this behavior," + + " use GsonBuilder.serializeSpecialFloatingPointValues() method."); + + e = assertThrows(IllegalArgumentException.class, () -> gson.toJson((Double) Double.NaN)); + assertThat(e) + .hasMessageThat() + .isEqualTo( + "NaN is not a valid double value as per JSON specification. To override this behavior," + + " use GsonBuilder.serializeSpecialFloatingPointValues() method."); } @Test public void testDoubleNaNSerialization() { Gson gson = new GsonBuilder().serializeSpecialFloatingPointValues().create(); - double nan = Double.NaN; - assertThat(gson.toJson(nan)).isEqualTo("NaN"); assertThat(gson.toJson(Double.NaN)).isEqualTo("NaN"); + assertThat(gson.toJson((Double) Double.NaN)).isEqualTo("NaN"); } @Test public void testDoubleNaNDeserialization() { - assertThat(gson.fromJson("NaN", Double.class)).isNaN(); assertThat(gson.fromJson("NaN", double.class)).isNaN(); + assertThat(gson.fromJson("NaN", Double.class)).isNaN(); } @Test public void testFloatNaNSerializationNotSupportedByDefault() { - try { - float nan = Float.NaN; - gson.toJson(nan); - fail("Gson should not accept NaN for serialization"); - } catch (IllegalArgumentException expected) { - } - try { - gson.toJson(Float.NaN); - fail("Gson should not accept NaN for serialization"); - } catch (IllegalArgumentException expected) { - } + var e = assertThrows(IllegalArgumentException.class, () -> gson.toJson(Float.NaN)); + assertThat(e) + .hasMessageThat() + .isEqualTo( + "NaN is not a valid double value as per JSON specification. To override this behavior," + + " use GsonBuilder.serializeSpecialFloatingPointValues() method."); + + e = assertThrows(IllegalArgumentException.class, () -> gson.toJson((Float) Float.NaN)); + assertThat(e) + .hasMessageThat() + .isEqualTo( + "NaN is not a valid double value as per JSON specification. To override this behavior," + + " use GsonBuilder.serializeSpecialFloatingPointValues() method."); } @Test public void testFloatNaNSerialization() { Gson gson = new GsonBuilder().serializeSpecialFloatingPointValues().create(); - float nan = Float.NaN; - assertThat(gson.toJson(nan)).isEqualTo("NaN"); assertThat(gson.toJson(Float.NaN)).isEqualTo("NaN"); + assertThat(gson.toJson((Float) Float.NaN)).isEqualTo("NaN"); } @Test public void testFloatNaNDeserialization() { - assertThat(gson.fromJson("NaN", Float.class)).isNaN(); assertThat(gson.fromJson("NaN", float.class)).isNaN(); + assertThat(gson.fromJson("NaN", Float.class)).isNaN(); } @Test public void testBigDecimalNaNDeserializationNotSupported() { - try { - gson.fromJson("NaN", BigDecimal.class); - fail("Gson should not accept NaN for deserialization by default."); - } catch (JsonSyntaxException expected) { - } + // Gson should not accept NaN for deserialization by default + assertThrows(JsonSyntaxException.class, () -> gson.fromJson("NaN", BigDecimal.class)); } @Test public void testDoubleInfinitySerializationNotSupportedByDefault() { - try { - double infinity = Double.POSITIVE_INFINITY; - gson.toJson(infinity); - fail("Gson should not accept positive infinity for serialization by default."); - } catch (IllegalArgumentException expected) { - } - try { - gson.toJson(Double.POSITIVE_INFINITY); - fail("Gson should not accept positive infinity for serialization by default."); - } catch (IllegalArgumentException expected) { - } + var e = + assertThrows(IllegalArgumentException.class, () -> gson.toJson(Double.POSITIVE_INFINITY)); + assertThat(e) + .hasMessageThat() + .isEqualTo( + "Infinity is not a valid double value as per JSON specification. To override this" + + " behavior, use GsonBuilder.serializeSpecialFloatingPointValues() method."); + + e = + assertThrows( + IllegalArgumentException.class, () -> gson.toJson((Double) Double.POSITIVE_INFINITY)); + assertThat(e) + .hasMessageThat() + .isEqualTo( + "Infinity is not a valid double value as per JSON specification. To override this" + + " behavior, use GsonBuilder.serializeSpecialFloatingPointValues() method."); } @Test public void testDoubleInfinitySerialization() { Gson gson = new GsonBuilder().serializeSpecialFloatingPointValues().create(); - double infinity = Double.POSITIVE_INFINITY; - assertThat(gson.toJson(infinity)).isEqualTo("Infinity"); assertThat(gson.toJson(Double.POSITIVE_INFINITY)).isEqualTo("Infinity"); + assertThat(gson.toJson((Double) Double.POSITIVE_INFINITY)).isEqualTo("Infinity"); } @Test public void testDoubleInfinityDeserialization() { - assertThat(gson.fromJson("Infinity", Double.class)).isPositiveInfinity(); assertThat(gson.fromJson("Infinity", double.class)).isPositiveInfinity(); + assertThat(gson.fromJson("Infinity", Double.class)).isPositiveInfinity(); } @Test public void testFloatInfinitySerializationNotSupportedByDefault() { - try { - float infinity = Float.POSITIVE_INFINITY; - gson.toJson(infinity); - fail("Gson should not accept positive infinity for serialization by default"); - } catch (IllegalArgumentException expected) { - } - try { - gson.toJson(Float.POSITIVE_INFINITY); - fail("Gson should not accept positive infinity for serialization by default"); - } catch (IllegalArgumentException expected) { - } + var e = + assertThrows(IllegalArgumentException.class, () -> gson.toJson(Float.POSITIVE_INFINITY)); + assertThat(e) + .hasMessageThat() + .isEqualTo( + "Infinity is not a valid double value as per JSON specification. To override this" + + " behavior, use GsonBuilder.serializeSpecialFloatingPointValues() method."); + + e = + assertThrows( + IllegalArgumentException.class, () -> gson.toJson((Float) Float.POSITIVE_INFINITY)); + assertThat(e) + .hasMessageThat() + .isEqualTo( + "Infinity is not a valid double value as per JSON specification. To override this" + + " behavior, use GsonBuilder.serializeSpecialFloatingPointValues() method."); } @Test public void testFloatInfinitySerialization() { Gson gson = new GsonBuilder().serializeSpecialFloatingPointValues().create(); - float infinity = Float.POSITIVE_INFINITY; - assertThat(gson.toJson(infinity)).isEqualTo("Infinity"); assertThat(gson.toJson(Float.POSITIVE_INFINITY)).isEqualTo("Infinity"); + assertThat(gson.toJson((Float) Float.POSITIVE_INFINITY)).isEqualTo("Infinity"); } @Test public void testFloatInfinityDeserialization() { - assertThat(gson.fromJson("Infinity", Float.class)).isPositiveInfinity(); assertThat(gson.fromJson("Infinity", float.class)).isPositiveInfinity(); + assertThat(gson.fromJson("Infinity", Float.class)).isPositiveInfinity(); } @Test public void testBigDecimalInfinityDeserializationNotSupported() { - try { - gson.fromJson("Infinity", BigDecimal.class); - fail("Gson should not accept positive infinity for deserialization with BigDecimal"); - } catch (JsonSyntaxException expected) { - } + // Gson should not accept positive infinity for deserialization with BigDecimal + assertThrows(JsonSyntaxException.class, () -> gson.fromJson("Infinity", BigDecimal.class)); } @Test public void testNegativeInfinitySerializationNotSupportedByDefault() { - try { - double negativeInfinity = Double.NEGATIVE_INFINITY; - gson.toJson(negativeInfinity); - fail("Gson should not accept negative infinity for serialization by default"); - } catch (IllegalArgumentException expected) { - } - try { - gson.toJson(Double.NEGATIVE_INFINITY); - fail("Gson should not accept negative infinity for serialization by default"); - } catch (IllegalArgumentException expected) { - } + var e = + assertThrows(IllegalArgumentException.class, () -> gson.toJson(Double.NEGATIVE_INFINITY)); + assertThat(e) + .hasMessageThat() + .isEqualTo( + "-Infinity is not a valid double value as per JSON specification. To override this" + + " behavior, use GsonBuilder.serializeSpecialFloatingPointValues() method."); + + e = + assertThrows( + IllegalArgumentException.class, () -> gson.toJson((Double) Double.NEGATIVE_INFINITY)); + assertThat(e) + .hasMessageThat() + .isEqualTo( + "-Infinity is not a valid double value as per JSON specification. To override this" + + " behavior, use GsonBuilder.serializeSpecialFloatingPointValues() method."); } @Test public void testNegativeInfinitySerialization() { Gson gson = new GsonBuilder().serializeSpecialFloatingPointValues().create(); - double negativeInfinity = Double.NEGATIVE_INFINITY; - assertThat(gson.toJson(negativeInfinity)).isEqualTo("-Infinity"); assertThat(gson.toJson(Double.NEGATIVE_INFINITY)).isEqualTo("-Infinity"); + assertThat(gson.toJson((Double) Double.NEGATIVE_INFINITY)).isEqualTo("-Infinity"); } @Test @@ -695,25 +699,29 @@ public void testNegativeInfinityDeserialization() { @Test public void testNegativeInfinityFloatSerializationNotSupportedByDefault() { - try { - float negativeInfinity = Float.NEGATIVE_INFINITY; - gson.toJson(negativeInfinity); - fail("Gson should not accept negative infinity for serialization by default"); - } catch (IllegalArgumentException expected) { - } - try { - gson.toJson(Float.NEGATIVE_INFINITY); - fail("Gson should not accept negative infinity for serialization by default"); - } catch (IllegalArgumentException expected) { - } + var e = + assertThrows(IllegalArgumentException.class, () -> gson.toJson(Float.NEGATIVE_INFINITY)); + assertThat(e) + .hasMessageThat() + .isEqualTo( + "-Infinity is not a valid double value as per JSON specification. To override this" + + " behavior, use GsonBuilder.serializeSpecialFloatingPointValues() method."); + + e = + assertThrows( + IllegalArgumentException.class, () -> gson.toJson((Float) Float.NEGATIVE_INFINITY)); + assertThat(e) + .hasMessageThat() + .isEqualTo( + "-Infinity is not a valid double value as per JSON specification. To override this" + + " behavior, use GsonBuilder.serializeSpecialFloatingPointValues() method."); } @Test public void testNegativeInfinityFloatSerialization() { Gson gson = new GsonBuilder().serializeSpecialFloatingPointValues().create(); - float negativeInfinity = Float.NEGATIVE_INFINITY; - assertThat(gson.toJson(negativeInfinity)).isEqualTo("-Infinity"); assertThat(gson.toJson(Float.NEGATIVE_INFINITY)).isEqualTo("-Infinity"); + assertThat(gson.toJson((Float) Float.NEGATIVE_INFINITY)).isEqualTo("-Infinity"); } @Test @@ -724,11 +732,8 @@ public void testNegativeInfinityFloatDeserialization() { @Test public void testBigDecimalNegativeInfinityDeserializationNotSupported() { - try { - gson.fromJson("-Infinity", BigDecimal.class); - fail("Gson should not accept positive infinity for deserialization"); - } catch (JsonSyntaxException expected) { - } + // Gson should not accept positive infinity for deserialization + assertThrows(JsonSyntaxException.class, () -> gson.fromJson("-Infinity", BigDecimal.class)); } @Test diff --git a/gson/src/test/java/com/google/gson/functional/ReadersWritersTest.java b/gson/src/test/java/com/google/gson/functional/ReadersWritersTest.java index 660a0ae430..eb326ff0f3 100644 --- a/gson/src/test/java/com/google/gson/functional/ReadersWritersTest.java +++ b/gson/src/test/java/com/google/gson/functional/ReadersWritersTest.java @@ -16,7 +16,7 @@ package com.google.gson.functional; import static com.google.common.truth.Truth.assertThat; -import static org.junit.Assert.fail; +import static org.junit.Assert.assertThrows; import com.google.errorprone.annotations.CanIgnoreReturnValue; import com.google.gson.Gson; @@ -32,6 +32,7 @@ import java.io.StringReader; import java.io.StringWriter; import java.io.Writer; +import java.lang.reflect.Type; import java.util.Arrays; import java.util.Map; import org.junit.Before; @@ -130,20 +131,14 @@ public void testReadWriteTwoObjects() throws IOException { @Test public void testTypeMismatchThrowsJsonSyntaxExceptionForStrings() { - try { - gson.fromJson("true", new TypeToken>() {}.getType()); - fail(); - } catch (JsonSyntaxException expected) { - } + Type type = new TypeToken>() {}.getType(); + assertThrows(JsonSyntaxException.class, () -> gson.fromJson("true", type)); } @Test public void testTypeMismatchThrowsJsonSyntaxExceptionForReaders() { - try { - gson.fromJson(new StringReader("true"), new TypeToken>() {}.getType()); - fail(); - } catch (JsonSyntaxException expected) { - } + Type type = new TypeToken>() {}.getType(); + assertThrows(JsonSyntaxException.class, () -> gson.fromJson(new StringReader("true"), type)); } /** diff --git a/gson/src/test/java/com/google/gson/functional/ReflectionAccessFilterTest.java b/gson/src/test/java/com/google/gson/functional/ReflectionAccessFilterTest.java index ba06a190d2..546c39e137 100644 --- a/gson/src/test/java/com/google/gson/functional/ReflectionAccessFilterTest.java +++ b/gson/src/test/java/com/google/gson/functional/ReflectionAccessFilterTest.java @@ -17,7 +17,7 @@ package com.google.gson.functional; import static com.google.common.truth.Truth.assertThat; -import static org.junit.Assert.fail; +import static org.junit.Assert.assertThrows; import static org.junit.Assume.assumeNotNull; import com.google.gson.Gson; @@ -65,26 +65,26 @@ public void testBlockInaccessibleJava() throws ReflectiveOperationException { .create(); // Serialization should fail for classes with non-public fields - try { - gson.toJson(new File("a")); - 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 - 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."); - } + // Note: This test is rather brittle and depends on the JDK implementation + var e = + assertThrows( + "Expected exception; test needs to be run with Java >= 9", + JsonIOException.class, + () -> gson.toJson(new File("a"))); + assertThat(e) + .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."); // But serialization should succeed for classes with only public fields. // Not many JDK classes have mutable public fields, thank goodness, but java.awt.Point does. Class pointClass = null; try { pointClass = Class.forName("java.awt.Point"); - } catch (ClassNotFoundException e) { + } catch (ClassNotFoundException ignored) { } assumeNotNull(pointClass); Constructor pointConstructor = pointClass.getConstructor(int.class, int.class); @@ -100,18 +100,18 @@ public void testBlockInaccessibleJavaExtendingJdkClass() { .addReflectionAccessFilter(ReflectionAccessFilter.BLOCK_INACCESSIBLE_JAVA) .create(); - try { - gson.toJson(new ClassExtendingJdkClass()); - fail("Expected exception; test needs to be run with Java >= 9"); - } catch (JsonIOException expected) { - 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."); - } + var e = + assertThrows( + "Expected exception; test needs to be run with Java >= 9", + JsonIOException.class, + () -> gson.toJson(new ClassExtendingJdkClass())); + assertThat(e) + .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."); } @Test @@ -119,17 +119,13 @@ public void testBlockAllJava() { Gson gson = new GsonBuilder().addReflectionAccessFilter(ReflectionAccessFilter.BLOCK_ALL_JAVA).create(); - // Serialization should fail for any Java class - try { - gson.toJson(Thread.currentThread()); - fail(); - } catch (JsonIOException expected) { - 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."); - } + // Serialization should fail for any Java class without custom adapter + var e = assertThrows(JsonIOException.class, () -> gson.toJson(Thread.currentThread())); + assertThat(e) + .hasMessageThat() + .isEqualTo( + "ReflectionAccessFilter does not permit using reflection for class java.lang.Thread." + + " Register a TypeAdapter for this type or adjust the access filter."); } @Test @@ -137,18 +133,14 @@ public void testBlockAllJavaExtendingJdkClass() { Gson gson = new GsonBuilder().addReflectionAccessFilter(ReflectionAccessFilter.BLOCK_ALL_JAVA).create(); - try { - gson.toJson(new ClassExtendingJdkClass()); - fail(); - } catch (JsonIOException expected) { - 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."); - } + var e = assertThrows(JsonIOException.class, () -> gson.toJson(new ClassExtendingJdkClass())); + assertThat(e) + .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."); } private static class ClassWithStaticField { @@ -171,18 +163,18 @@ public FilterResult check(Class rawClass) { .excludeFieldsWithModifiers(0) .create(); - try { - gson.toJson(new ClassWithStaticField()); - fail("Expected exception; test needs to be run with Java >= 9"); - } catch (JsonIOException expected) { - 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."); - } + var e = + assertThrows( + "Expected exception; test needs to be run with Java >= 9", + JsonIOException.class, + () -> gson.toJson(new ClassWithStaticField())); + assertThat(e) + .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."); } private static class SuperTestClass {} @@ -224,17 +216,13 @@ public FilterResult check(Class rawClass) { .create(); // Filter disallows SuperTestClass - try { - gson.toJson(new SuperTestClass()); - fail(); - } catch (JsonIOException expected) { - 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."); - } + var e = assertThrows(JsonIOException.class, () -> gson.toJson(new SuperTestClass())); + assertThat(e) + .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."); // But registration order is reversed, so filter for SubTestClass allows reflection String json = gson.toJson(new SubTestClass()); @@ -266,21 +254,21 @@ public FilterResult check(Class rawClass) { .create(); // First make sure test is implemented correctly and access is blocked - try { - gson.toJson(new ExtendingClassWithPrivateField()); - fail("Expected exception; test needs to be run with Java >= 9"); - } catch (JsonIOException expected) { - 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."); - } - - gson = + var e = + assertThrows( + "Expected exception; test needs to be run with Java >= 9", + JsonIOException.class, + () -> gson.toJson(new ExtendingClassWithPrivateField())); + assertThat(e) + .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."); + + Gson gson2 = gson.newBuilder() // Allow reflective access for supertype .addReflectionAccessFilter( @@ -295,7 +283,7 @@ public FilterResult check(Class rawClass) { .create(); // Inherited (inaccessible) private field should have been made accessible - String json = gson.toJson(new ExtendingClassWithPrivateField()); + String json = gson2.toJson(new ExtendingClassWithPrivateField()); assertThat(json).isEqualTo("{\"i\":1}"); } @@ -316,19 +304,19 @@ public FilterResult check(Class rawClass) { }) .create(); - try { - gson.fromJson("{}", ClassWithPrivateNoArgsConstructor.class); - fail("Expected exception; test needs to be run with Java >= 9"); - } catch (JsonIOException expected) { - 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."); - } + var e = + assertThrows( + "Expected exception; test needs to be run with Java >= 9", + JsonIOException.class, + () -> gson.fromJson("{}", ClassWithPrivateNoArgsConstructor.class)); + assertThat(e) + .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."); } private static class ClassWithoutNoArgsConstructor { @@ -353,22 +341,20 @@ public FilterResult check(Class rawClass) { }); Gson gson = gsonBuilder.create(); - try { - gson.fromJson("{}", ClassWithoutNoArgsConstructor.class); - fail(); - } catch (JsonIOException expected) { - 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."); - } + var e = + assertThrows( + JsonIOException.class, () -> gson.fromJson("{}", ClassWithoutNoArgsConstructor.class)); + assertThat(e) + .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."); // But should not fail when custom TypeAdapter is specified - gson = + Gson gson2 = gson.newBuilder() .registerTypeAdapter( ClassWithoutNoArgsConstructor.class, @@ -386,11 +372,11 @@ public void write(JsonWriter out, ClassWithoutNoArgsConstructor value) { }) .create(); ClassWithoutNoArgsConstructor deserialized = - gson.fromJson("{}", ClassWithoutNoArgsConstructor.class); + gson2.fromJson("{}", ClassWithoutNoArgsConstructor.class); assertThat(deserialized.s).isEqualTo("TypeAdapter"); // But should not fail when custom InstanceCreator is specified - gson = + gson2 = gsonBuilder .registerTypeAdapter( ClassWithoutNoArgsConstructor.class, @@ -401,7 +387,7 @@ public ClassWithoutNoArgsConstructor createInstance(Type type) { } }) .create(); - deserialized = gson.fromJson("{}", ClassWithoutNoArgsConstructor.class); + deserialized = gson2.fromJson("{}", ClassWithoutNoArgsConstructor.class); assertThat(deserialized.s).isEqualTo("InstanceCreator"); } @@ -435,17 +421,13 @@ public JsonElement serialize( assertThat(json).isEqualTo("123"); // But deserialization should fail - try { - gson.fromJson("{}", OtherClass.class); - fail(); - } catch (JsonIOException expected) { - 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."); - } + var e = assertThrows(JsonIOException.class, () -> gson.fromJson("{}", OtherClass.class)); + assertThat(e) + .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."); } /** @@ -505,16 +487,12 @@ public FilterResult check(Class rawClass) { }) .create(); - try { - gson.fromJson("{}", Runnable.class); - fail(); - } catch (JsonIOException expected) { - assertThat(expected) - .hasMessageThat() - .isEqualTo( - "Interfaces can't be instantiated! Register an InstanceCreator or a TypeAdapter for" - + " this type. Interface name: java.lang.Runnable"); - } + var e = assertThrows(JsonIOException.class, () -> gson.fromJson("{}", Runnable.class)); + assertThat(e) + .hasMessageThat() + .isEqualTo( + "Interfaces can't be instantiated! Register an InstanceCreator or a TypeAdapter for" + + " this type. Interface name: java.lang.Runnable"); } /** diff --git a/gson/src/test/java/com/google/gson/functional/ReflectionAccessTest.java b/gson/src/test/java/com/google/gson/functional/ReflectionAccessTest.java index f7b2e33502..b37a3c0bec 100644 --- a/gson/src/test/java/com/google/gson/functional/ReflectionAccessTest.java +++ b/gson/src/test/java/com/google/gson/functional/ReflectionAccessTest.java @@ -17,7 +17,7 @@ package com.google.gson.functional; import static com.google.common.truth.Truth.assertThat; -import static org.junit.Assert.fail; +import static org.junit.Assert.assertThrows; import static org.junit.Assume.assumeTrue; import com.google.gson.Gson; @@ -79,16 +79,12 @@ public void checkPermission(Permission perm) { try { Gson gson = new Gson(); - try { - // Getting reflection based adapter should fail - gson.getAdapter(clazz); - fail(); - } catch (SecurityException e) { - assertThat(e).hasMessageThat().isEqualTo("Gson: no-member-access"); - } + // Getting reflection based adapter should fail + var e = assertThrows(SecurityException.class, () -> gson.getAdapter(clazz)); + assertThat(e).hasMessageThat().isEqualTo("Gson: no-member-access"); final AtomicBoolean wasReadCalled = new AtomicBoolean(false); - gson = + Gson gson2 = new GsonBuilder() .registerTypeAdapter( clazz, @@ -107,8 +103,8 @@ public Object read(JsonReader in) throws IOException { }) .create(); - assertThat(gson.toJson(null, clazz)).isEqualTo("\"custom-write\""); - assertThat(gson.fromJson("{}", clazz)).isNull(); + assertThat(gson2.toJson(null, clazz)).isEqualTo("\"custom-write\""); + assertThat(gson2.fromJson("{}", clazz)).isNull(); assertThat(wasReadCalled.get()).isTrue(); } finally { System.setSecurityManager(original); diff --git a/gson/src/test/java/com/google/gson/functional/StreamingTypeAdaptersTest.java b/gson/src/test/java/com/google/gson/functional/StreamingTypeAdaptersTest.java index b047e4c51e..78fa8a02be 100644 --- a/gson/src/test/java/com/google/gson/functional/StreamingTypeAdaptersTest.java +++ b/gson/src/test/java/com/google/gson/functional/StreamingTypeAdaptersTest.java @@ -17,7 +17,7 @@ package com.google.gson.functional; import static com.google.common.truth.Truth.assertThat; -import static org.junit.Assert.fail; +import static org.junit.Assert.assertThrows; import com.google.common.base.Splitter; import com.google.gson.Gson; @@ -193,36 +193,33 @@ public void write(JsonWriter out, Person person) throws IOException { out.value(person.name + "," + person.age); } }; + Gson gson = new GsonBuilder().registerTypeAdapter(Person.class, typeAdapter).create(); Truck truck = new Truck(); truck.horsePower = 1.0D; truck.passengers = new ArrayList<>(); truck.passengers.add(null); truck.passengers.add(new Person("jesse", 30)); - try { - gson.toJson(truck, Truck.class); - fail(); - } catch (NullPointerException expected) { - } + + assertThrows(NullPointerException.class, () -> gson.toJson(truck, Truck.class)); + String json = "{horsePower:1.0,passengers:[null,'jesse,30']}"; - try { - gson.fromJson(json, Truck.class); - fail(); - } catch (JsonSyntaxException expected) { - assertThat(expected) - .hasMessageThat() - .isEqualTo( - "java.lang.IllegalStateException: Expected a string but was NULL at line 1 column 33" - + " path $.passengers[0]\n" - + "See https://github.com/google/gson/blob/main/Troubleshooting.md#adapter-not-null-safe"); - } - gson = new GsonBuilder().registerTypeAdapter(Person.class, typeAdapter.nullSafe()).create(); - assertThat(gson.toJson(truck, Truck.class)) + var e = assertThrows(JsonSyntaxException.class, () -> gson.fromJson(json, Truck.class)); + assertThat(e) + .hasMessageThat() + .isEqualTo( + "java.lang.IllegalStateException: Expected a string but was NULL at line 1 column 33" + + " path $.passengers[0]\n" + + "See https://github.com/google/gson/blob/main/Troubleshooting.md#adapter-not-null-safe"); + + Gson gson2 = + new GsonBuilder().registerTypeAdapter(Person.class, typeAdapter.nullSafe()).create(); + assertThat(gson2.toJson(truck, Truck.class)) .isEqualTo("{\"horsePower\":1.0,\"passengers\":[null,\"jesse,30\"]}"); - truck = gson.fromJson(json, Truck.class); - assertThat(truck.horsePower).isEqualTo(1.0D); - assertThat(truck.passengers.get(0)).isNull(); - assertThat(truck.passengers.get(1).name).isEqualTo("jesse"); + Truck deserialized = gson2.fromJson(json, Truck.class); + assertThat(deserialized.horsePower).isEqualTo(1.0D); + assertThat(deserialized.passengers.get(0)).isNull(); + assertThat(deserialized.passengers.get(1).name).isEqualTo("jesse"); } @Test diff --git a/gson/src/test/java/com/google/gson/functional/ToNumberPolicyFunctionalTest.java b/gson/src/test/java/com/google/gson/functional/ToNumberPolicyFunctionalTest.java index d427e71246..3ee85e2fc3 100644 --- a/gson/src/test/java/com/google/gson/functional/ToNumberPolicyFunctionalTest.java +++ b/gson/src/test/java/com/google/gson/functional/ToNumberPolicyFunctionalTest.java @@ -17,7 +17,7 @@ package com.google.gson.functional; import static com.google.common.truth.Truth.assertThat; -import static org.junit.Assert.fail; +import static org.junit.Assert.assertThrows; import com.google.gson.Gson; import com.google.gson.GsonBuilder; @@ -118,11 +118,13 @@ public void testAsListOfLongsOrDoubles() { @Test public void testCustomStrategiesCannotAffectConcreteDeclaredNumbers() { + UnsupportedOperationException customException = + new UnsupportedOperationException("test-exception"); ToNumberStrategy fail = new ToNumberStrategy() { @Override public Byte readNumber(JsonReader in) { - throw new UnsupportedOperationException(); + throw customException; } }; Gson gson = @@ -130,15 +132,17 @@ public Byte readNumber(JsonReader in) { List numbers = gson.fromJson("[null, 10, 20, 30]", new TypeToken>() {}.getType()); assertThat(numbers).containsExactly(null, (byte) 10, (byte) 20, (byte) 30).inOrder(); - try { - gson.fromJson("[null, 10, 20, 30]", new TypeToken>() {}.getType()); - fail(); - } catch (UnsupportedOperationException ex) { - } - try { - gson.fromJson("[null, 10, 20, 30]", new TypeToken>() {}.getType()); - fail(); - } catch (UnsupportedOperationException ex) { - } + + var e = + assertThrows( + UnsupportedOperationException.class, + () -> gson.fromJson("[null, 10, 20, 30]", new TypeToken>() {}.getType())); + assertThat(e).isSameInstanceAs(customException); + + e = + assertThrows( + UnsupportedOperationException.class, + () -> gson.fromJson("[null, 10, 20, 30]", new TypeToken>() {}.getType())); + assertThat(e).isSameInstanceAs(customException); } } diff --git a/gson/src/test/java/com/google/gson/functional/UncategorizedTest.java b/gson/src/test/java/com/google/gson/functional/UncategorizedTest.java index 2ba6549fe9..9be2b36fd3 100644 --- a/gson/src/test/java/com/google/gson/functional/UncategorizedTest.java +++ b/gson/src/test/java/com/google/gson/functional/UncategorizedTest.java @@ -16,7 +16,7 @@ package com.google.gson.functional; import static com.google.common.truth.Truth.assertThat; -import static org.junit.Assert.fail; +import static org.junit.Assert.assertThrows; import com.google.gson.Gson; import com.google.gson.GsonBuilder; @@ -49,17 +49,12 @@ public void setUp() throws Exception { @Test public void testInvalidJsonDeserializationFails() throws Exception { - try { - gson.fromJson("adfasdf1112,,,\":", BagOfPrimitives.class); - fail("Bad JSON should throw a ParseException"); - } catch (JsonParseException expected) { - } + assertThrows( + JsonParseException.class, () -> gson.fromJson("adfasdf1112,,,\":", BagOfPrimitives.class)); - try { - gson.fromJson("{adfasdf1112,,,\":}", BagOfPrimitives.class); - fail("Bad JSON should throw a ParseException"); - } catch (JsonParseException expected) { - } + assertThrows( + JsonParseException.class, + () -> gson.fromJson("{adfasdf1112,,,\":}", BagOfPrimitives.class)); } @Test diff --git a/gson/src/test/java/com/google/gson/internal/ConstructorConstructorTest.java b/gson/src/test/java/com/google/gson/internal/ConstructorConstructorTest.java index 32253abb17..13a1fe2989 100644 --- a/gson/src/test/java/com/google/gson/internal/ConstructorConstructorTest.java +++ b/gson/src/test/java/com/google/gson/internal/ConstructorConstructorTest.java @@ -17,7 +17,7 @@ package com.google.gson.internal; import static com.google.common.truth.Truth.assertThat; -import static org.junit.Assert.fail; +import static org.junit.Assert.assertThrows; import com.google.gson.reflect.TypeToken; import java.util.Collections; @@ -42,34 +42,26 @@ private interface Interface {} public void testGet_AbstractClassNoArgConstructor() { ObjectConstructor constructor = constructorConstructor.get(TypeToken.get(AbstractClass.class)); - try { - constructor.construct(); - fail("Expected exception"); - } catch (RuntimeException exception) { - assertThat(exception) - .hasMessageThat() - .isEqualTo( - "Abstract classes can't be instantiated! Adjust the R8 configuration or register an" - + " InstanceCreator or a TypeAdapter for this type. Class name:" - + " com.google.gson.internal.ConstructorConstructorTest$AbstractClass\n" - + "See https://github.com/google/gson/blob/main/Troubleshooting.md#r8-abstract-class"); - } + var e = assertThrows(RuntimeException.class, () -> constructor.construct()); + assertThat(e) + .hasMessageThat() + .isEqualTo( + "Abstract classes can't be instantiated! Adjust the R8 configuration or register an" + + " InstanceCreator or a TypeAdapter for this type. Class name:" + + " com.google.gson.internal.ConstructorConstructorTest$AbstractClass\n" + + "See https://github.com/google/gson/blob/main/Troubleshooting.md#r8-abstract-class"); } @Test public void testGet_Interface() { ObjectConstructor constructor = constructorConstructor.get(TypeToken.get(Interface.class)); - try { - constructor.construct(); - fail("Expected exception"); - } catch (RuntimeException exception) { - assertThat(exception) - .hasMessageThat() - .isEqualTo( - "Interfaces can't be instantiated! Register an InstanceCreator or a TypeAdapter for" - + " this type. Interface name:" - + " com.google.gson.internal.ConstructorConstructorTest$Interface"); - } + var e = assertThrows(RuntimeException.class, () -> constructor.construct()); + assertThat(e) + .hasMessageThat() + .isEqualTo( + "Interfaces can't be instantiated! Register an InstanceCreator or a TypeAdapter for" + + " this type. Interface name:" + + " com.google.gson.internal.ConstructorConstructorTest$Interface"); } } diff --git a/gson/src/test/java/com/google/gson/internal/LinkedTreeMapTest.java b/gson/src/test/java/com/google/gson/internal/LinkedTreeMapTest.java index fd31817c83..2da7aae8cd 100644 --- a/gson/src/test/java/com/google/gson/internal/LinkedTreeMapTest.java +++ b/gson/src/test/java/com/google/gson/internal/LinkedTreeMapTest.java @@ -17,7 +17,7 @@ package com.google.gson.internal; import static com.google.common.truth.Truth.assertThat; -import static org.junit.Assert.fail; +import static org.junit.Assert.assertThrows; import com.google.gson.common.MoreAsserts; import java.io.ByteArrayInputStream; @@ -25,8 +25,6 @@ import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; -import java.util.ArrayList; -import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.Map; @@ -42,8 +40,8 @@ public void testIterationOrder() { map.put("a", "android"); map.put("c", "cola"); map.put("b", "bbq"); - assertIterationOrder(map.keySet(), "a", "c", "b"); - assertIterationOrder(map.values(), "android", "cola", "bbq"); + assertThat(map.keySet()).containsExactly("a", "c", "b").inOrder(); + assertThat(map.values()).containsExactly("android", "cola", "bbq").inOrder(); } @Test @@ -57,29 +55,22 @@ public void testRemoveRootDoesNotDoubleUnlink() { it.next(); it.next(); it.remove(); - assertIterationOrder(map.keySet(), "a", "c"); + assertThat(map.keySet()).containsExactly("a", "c").inOrder(); } @Test @SuppressWarnings("ModifiedButNotUsed") public void testPutNullKeyFails() { LinkedTreeMap map = new LinkedTreeMap<>(); - try { - map.put(null, "android"); - fail(); - } catch (NullPointerException expected) { - } + var e = assertThrows(NullPointerException.class, () -> map.put(null, "android")); + assertThat(e).hasMessageThat().isEqualTo("key == null"); } @Test @SuppressWarnings("ModifiedButNotUsed") public void testPutNonComparableKeyFails() { LinkedTreeMap map = new LinkedTreeMap<>(); - try { - map.put(new Object(), "android"); - fail(); - } catch (ClassCastException expected) { - } + assertThrows(ClassCastException.class, () -> map.put(new Object(), "android")); } @Test @@ -96,12 +87,9 @@ public void testPutNullValue() { @Test public void testPutNullValue_Forbidden() { LinkedTreeMap map = new LinkedTreeMap<>(false); - try { - map.put("a", null); - fail(); - } catch (NullPointerException e) { - assertThat(e).hasMessageThat().isEqualTo("value == null"); - } + var e = assertThrows(NullPointerException.class, () -> map.put("a", null)); + assertThat(e).hasMessageThat().isEqualTo("value == null"); + assertThat(map).hasSize(0); assertThat(map).doesNotContainKey("a"); assertThat(map.containsValue(null)).isFalse(); @@ -128,12 +116,9 @@ public void testEntrySetValueNull_Forbidden() { LinkedTreeMap map = new LinkedTreeMap<>(false); map.put("a", "1"); Entry entry = map.entrySet().iterator().next(); - try { - entry.setValue(null); - fail(); - } catch (NullPointerException e) { - assertThat(e).hasMessageThat().isEqualTo("value == null"); - } + var e = assertThrows(NullPointerException.class, () -> entry.setValue(null)); + assertThat(e).hasMessageThat().isEqualTo("value == null"); + assertThat(entry.getValue()).isEqualTo("1"); assertThat(map.get("a")).isEqualTo("1"); assertThat(map.containsValue(null)).isFalse(); @@ -199,8 +184,8 @@ public void testClear() { map.put("c", "cola"); map.put("b", "bbq"); map.clear(); - assertIterationOrder(map.keySet()); - assertThat(map).hasSize(0); + assertThat(map.keySet()).isEmpty(); + assertThat(map).isEmpty(); } @Test @@ -234,14 +219,4 @@ public void testJavaSerialization() throws IOException, ClassNotFoundException { Map deserialized = (Map) objIn.readObject(); assertThat(deserialized).isEqualTo(Collections.singletonMap("a", 1)); } - - @SuppressWarnings("varargs") - @SafeVarargs - private static final void assertIterationOrder(Iterable actual, T... expected) { - ArrayList actualList = new ArrayList<>(); - for (T t : actual) { - actualList.add(t); - } - assertThat(actualList).isEqualTo(Arrays.asList(expected)); - } } diff --git a/gson/src/test/java/com/google/gson/internal/StreamsTest.java b/gson/src/test/java/com/google/gson/internal/StreamsTest.java index 0aeb4fdfd9..049a7ee0a1 100644 --- a/gson/src/test/java/com/google/gson/internal/StreamsTest.java +++ b/gson/src/test/java/com/google/gson/internal/StreamsTest.java @@ -17,7 +17,7 @@ package com.google.gson.internal; import static com.google.common.truth.Truth.assertThat; -import static org.junit.Assert.fail; +import static org.junit.Assert.assertThrows; import java.io.IOException; import java.io.Writer; @@ -44,33 +44,17 @@ public void testWriterForAppendable() throws IOException { writer.append(','); writer.write("chars".toCharArray()); - try { - writer.write((char[]) null); - fail(); - } catch (NullPointerException e) { - } + assertThrows(NullPointerException.class, () -> writer.write((char[]) null)); writer.write("chars".toCharArray(), 1, 2); - try { - writer.write((char[]) null, 1, 2); - fail(); - } catch (NullPointerException e) { - } + assertThrows(NullPointerException.class, () -> writer.write((char[]) null, 1, 2)); writer.append(','); writer.write("string"); - try { - writer.write((String) null); - fail(); - } catch (NullPointerException e) { - } + assertThrows(NullPointerException.class, () -> writer.write((String) null)); writer.write("string", 1, 2); - try { - writer.write((String) null, 1, 2); - fail(); - } catch (NullPointerException e) { - } + assertThrows(NullPointerException.class, () -> writer.write((String) null, 1, 2)); String actualOutput = stringBuilder.toString(); assertThat(actualOutput).isEqualTo("a\u1234testnullcdul,a\u1234\u1234,charsha,stringtr"); diff --git a/gson/src/test/java/com/google/gson/internal/bind/JsonElementReaderTest.java b/gson/src/test/java/com/google/gson/internal/bind/JsonElementReaderTest.java index 39d76e669a..a108ea5667 100644 --- a/gson/src/test/java/com/google/gson/internal/bind/JsonElementReaderTest.java +++ b/gson/src/test/java/com/google/gson/internal/bind/JsonElementReaderTest.java @@ -17,7 +17,7 @@ package com.google.gson.internal.bind; import static com.google.common.truth.Truth.assertThat; -import static org.junit.Assert.fail; +import static org.junit.Assert.assertThrows; import com.google.gson.JsonElement; import com.google.gson.JsonParser; @@ -60,26 +60,20 @@ public void testStrictNansAndInfinities() throws IOException { JsonTreeReader reader = new JsonTreeReader(element); reader.setStrictness(Strictness.LEGACY_STRICT); reader.beginArray(); - try { - reader.nextDouble(); - fail(); - } catch (MalformedJsonException e) { - assertThat(e).hasMessageThat().isEqualTo("JSON forbids NaN and infinities: NaN"); - } + + var e = assertThrows(MalformedJsonException.class, () -> reader.nextDouble()); + assertThat(e).hasMessageThat().isEqualTo("JSON forbids NaN and infinities: NaN"); + assertThat(reader.nextString()).isEqualTo("NaN"); - try { - reader.nextDouble(); - fail(); - } catch (MalformedJsonException e) { - assertThat(e).hasMessageThat().isEqualTo("JSON forbids NaN and infinities: -Infinity"); - } + + e = assertThrows(MalformedJsonException.class, () -> reader.nextDouble()); + assertThat(e).hasMessageThat().isEqualTo("JSON forbids NaN and infinities: -Infinity"); + assertThat(reader.nextString()).isEqualTo("-Infinity"); - try { - reader.nextDouble(); - fail(); - } catch (MalformedJsonException e) { - assertThat(e).hasMessageThat().isEqualTo("JSON forbids NaN and infinities: Infinity"); - } + + e = assertThrows(MalformedJsonException.class, () -> reader.nextDouble()); + assertThat(e).hasMessageThat().isEqualTo("JSON forbids NaN and infinities: Infinity"); + assertThat(reader.nextString()).isEqualTo("Infinity"); reader.endArray(); } @@ -236,89 +230,28 @@ public void testWrongType() throws IOException { JsonElement element = JsonParser.parseString("[[],\"A\"]"); JsonTreeReader reader = new JsonTreeReader(element); reader.beginArray(); - try { - reader.nextBoolean(); - fail(); - } catch (IllegalStateException expected) { - } - try { - reader.nextNull(); - fail(); - } catch (IllegalStateException expected) { - } - try { - reader.nextString(); - fail(); - } catch (IllegalStateException expected) { - } - try { - reader.nextInt(); - fail(); - } catch (IllegalStateException expected) { - } - try { - reader.nextLong(); - fail(); - } catch (IllegalStateException expected) { - } - try { - reader.nextDouble(); - fail(); - } catch (IllegalStateException expected) { - } - try { - reader.nextName(); - fail(); - } catch (IllegalStateException expected) { - } - try { - reader.beginObject(); - fail(); - } catch (IllegalStateException expected) { - } - try { - reader.endArray(); - fail(); - } catch (IllegalStateException expected) { - } - try { - reader.endObject(); - fail(); - } catch (IllegalStateException expected) { - } + + assertThrows(IllegalStateException.class, () -> reader.nextBoolean()); + assertThrows(IllegalStateException.class, () -> reader.nextNull()); + assertThrows(IllegalStateException.class, () -> reader.nextString()); + assertThrows(IllegalStateException.class, () -> reader.nextInt()); + assertThrows(IllegalStateException.class, () -> reader.nextLong()); + assertThrows(IllegalStateException.class, () -> reader.nextDouble()); + assertThrows(IllegalStateException.class, () -> reader.nextName()); + assertThrows(IllegalStateException.class, () -> reader.beginObject()); + assertThrows(IllegalStateException.class, () -> reader.endArray()); + assertThrows(IllegalStateException.class, () -> reader.endObject()); + reader.beginArray(); reader.endArray(); - try { - reader.nextBoolean(); - fail(); - } catch (IllegalStateException expected) { - } - try { - reader.nextNull(); - fail(); - } catch (IllegalStateException expected) { - } - try { - reader.nextInt(); - fail(); - } catch (NumberFormatException expected) { - } - try { - reader.nextLong(); - fail(); - } catch (NumberFormatException expected) { - } - try { - reader.nextDouble(); - fail(); - } catch (NumberFormatException expected) { - } - try { - reader.nextName(); - fail(); - } catch (IllegalStateException expected) { - } + assertThrows(IllegalStateException.class, () -> reader.nextBoolean()); + assertThrows(IllegalStateException.class, () -> reader.nextNull()); + assertThrows(NumberFormatException.class, () -> reader.nextInt()); + assertThrows(NumberFormatException.class, () -> reader.nextLong()); + assertThrows(NumberFormatException.class, () -> reader.nextDouble()); + assertThrows(IllegalStateException.class, () -> reader.nextName()); + assertThat(reader.nextString()).isEqualTo("A"); reader.endArray(); } @@ -328,35 +261,22 @@ public void testNextJsonElement() throws IOException { final JsonElement element = JsonParser.parseString("{\"A\": 1, \"B\" : {}, \"C\" : []}"); JsonTreeReader reader = new JsonTreeReader(element); reader.beginObject(); - try { - reader.nextJsonElement(); - fail(); - } catch (IllegalStateException expected) { - } - String unused1 = reader.nextName(); + + assertThrows(IllegalStateException.class, () -> reader.nextJsonElement()); + assertThat(reader.nextName()).isEqualTo("A"); assertThat(new JsonPrimitive(1)).isEqualTo(reader.nextJsonElement()); - String unused2 = reader.nextName(); + + assertThat(reader.nextName()).isEqualTo("B"); reader.beginObject(); - try { - reader.nextJsonElement(); - fail(); - } catch (IllegalStateException expected) { - } + assertThrows(IllegalStateException.class, () -> reader.nextJsonElement()); reader.endObject(); - String unused3 = reader.nextName(); + + assertThat(reader.nextName()).isEqualTo("C"); reader.beginArray(); - try { - reader.nextJsonElement(); - fail(); - } catch (IllegalStateException expected) { - } + assertThrows(IllegalStateException.class, () -> reader.nextJsonElement()); reader.endArray(); reader.endObject(); - try { - reader.nextJsonElement(); - fail(); - } catch (IllegalStateException expected) { - } + assertThrows(IllegalStateException.class, () -> reader.nextJsonElement()); } @Test @@ -365,10 +285,7 @@ public void testEarlyClose() throws IOException { JsonTreeReader reader = new JsonTreeReader(element); reader.beginArray(); reader.close(); - try { - reader.peek(); - fail(); - } catch (IllegalStateException expected) { - } + var e = assertThrows(IllegalStateException.class, () -> reader.peek()); + assertThat(e).hasMessageThat().isEqualTo("JsonReader is closed"); } } diff --git a/gson/src/test/java/com/google/gson/internal/bind/JsonTreeReaderTest.java b/gson/src/test/java/com/google/gson/internal/bind/JsonTreeReaderTest.java index 23ae773f65..04b0d87132 100644 --- a/gson/src/test/java/com/google/gson/internal/bind/JsonTreeReaderTest.java +++ b/gson/src/test/java/com/google/gson/internal/bind/JsonTreeReaderTest.java @@ -16,7 +16,7 @@ package com.google.gson.internal.bind; import static com.google.common.truth.Truth.assertThat; -import static org.junit.Assert.fail; +import static org.junit.Assert.assertThrows; import com.google.gson.JsonArray; import com.google.gson.JsonElement; @@ -128,18 +128,13 @@ public JsonElement deepCopy() { JsonTreeReader reader = new JsonTreeReader(array); reader.beginArray(); - try { - // Should fail due to custom JsonElement subclass - reader.peek(); - fail(); - } catch (MalformedJsonException expected) { - assertThat(expected) - .hasMessageThat() - .isEqualTo( - "Custom JsonElement subclass " - + CustomSubclass.class.getName() - + " is not supported"); - } + + // Should fail due to custom JsonElement subclass + var e = assertThrows(MalformedJsonException.class, () -> reader.peek()); + assertThat(e) + .hasMessageThat() + .isEqualTo( + "Custom JsonElement subclass " + CustomSubclass.class.getName() + " is not supported"); } /** diff --git a/gson/src/test/java/com/google/gson/internal/bind/JsonTreeWriterTest.java b/gson/src/test/java/com/google/gson/internal/bind/JsonTreeWriterTest.java index a212bce674..97dc2e56c0 100644 --- a/gson/src/test/java/com/google/gson/internal/bind/JsonTreeWriterTest.java +++ b/gson/src/test/java/com/google/gson/internal/bind/JsonTreeWriterTest.java @@ -18,7 +18,6 @@ import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.assertThrows; -import static org.junit.Assert.fail; import com.google.gson.JsonElement; import com.google.gson.JsonNull; @@ -93,11 +92,7 @@ public void testWriteAfterClose() throws Exception { writer.value("A"); writer.endArray(); writer.close(); - try { - writer.beginArray(); - fail(); - } catch (IllegalStateException expected) { - } + assertThrows(IllegalStateException.class, () -> writer.beginArray()); } @Test @@ -105,12 +100,8 @@ public void testPrematureClose() throws Exception { JsonTreeWriter writer = new JsonTreeWriter(); writer.setStrictness(Strictness.LENIENT); writer.beginArray(); - try { - writer.close(); - fail(); - } catch (IOException expected) { - assertThat(expected).hasMessageThat().isEqualTo("Incomplete document"); - } + var e = assertThrows(IOException.class, () -> writer.close()); + assertThat(e).hasMessageThat().isEqualTo("Incomplete document"); } @Test @@ -234,36 +225,12 @@ public void testStrictNansAndInfinities() throws IOException { JsonTreeWriter writer = new JsonTreeWriter(); writer.setStrictness(Strictness.LEGACY_STRICT); writer.beginArray(); - try { - writer.value(Float.NaN); - fail(); - } catch (IllegalArgumentException expected) { - } - try { - writer.value(Float.NEGATIVE_INFINITY); - fail(); - } catch (IllegalArgumentException expected) { - } - try { - writer.value(Float.POSITIVE_INFINITY); - fail(); - } catch (IllegalArgumentException expected) { - } - try { - writer.value(Double.NaN); - fail(); - } catch (IllegalArgumentException expected) { - } - try { - writer.value(Double.NEGATIVE_INFINITY); - fail(); - } catch (IllegalArgumentException expected) { - } - try { - writer.value(Double.POSITIVE_INFINITY); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> writer.value(Float.NaN)); + assertThrows(IllegalArgumentException.class, () -> writer.value(Float.NEGATIVE_INFINITY)); + assertThrows(IllegalArgumentException.class, () -> writer.value(Float.POSITIVE_INFINITY)); + assertThrows(IllegalArgumentException.class, () -> writer.value(Double.NaN)); + assertThrows(IllegalArgumentException.class, () -> writer.value(Double.NEGATIVE_INFINITY)); + assertThrows(IllegalArgumentException.class, () -> writer.value(Double.POSITIVE_INFINITY)); } @Test @@ -271,47 +238,25 @@ public void testStrictBoxedNansAndInfinities() throws IOException { JsonTreeWriter writer = new JsonTreeWriter(); writer.setStrictness(Strictness.LEGACY_STRICT); writer.beginArray(); - try { - writer.value(Float.valueOf(Float.NaN)); - fail(); - } catch (IllegalArgumentException expected) { - } - try { - writer.value(Float.valueOf(Float.NEGATIVE_INFINITY)); - fail(); - } catch (IllegalArgumentException expected) { - } - try { - writer.value(Float.valueOf(Float.POSITIVE_INFINITY)); - fail(); - } catch (IllegalArgumentException expected) { - } - try { - writer.value(Double.valueOf(Double.NaN)); - fail(); - } catch (IllegalArgumentException expected) { - } - try { - writer.value(Double.valueOf(Double.NEGATIVE_INFINITY)); - fail(); - } catch (IllegalArgumentException expected) { - } - try { - writer.value(Double.valueOf(Double.POSITIVE_INFINITY)); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> writer.value(Float.valueOf(Float.NaN))); + assertThrows( + IllegalArgumentException.class, () -> writer.value(Float.valueOf(Float.NEGATIVE_INFINITY))); + assertThrows( + IllegalArgumentException.class, () -> writer.value(Float.valueOf(Float.POSITIVE_INFINITY))); + assertThrows(IllegalArgumentException.class, () -> writer.value(Double.valueOf(Double.NaN))); + assertThrows( + IllegalArgumentException.class, + () -> writer.value(Double.valueOf(Double.NEGATIVE_INFINITY))); + assertThrows( + IllegalArgumentException.class, + () -> writer.value(Double.valueOf(Double.POSITIVE_INFINITY))); } @Test public void testJsonValue() throws IOException { JsonTreeWriter writer = new JsonTreeWriter(); writer.beginArray(); - try { - writer.jsonValue("test"); - fail(); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> writer.jsonValue("test")); } /** diff --git a/gson/src/test/java/com/google/gson/regression/OSGiTest.java b/gson/src/test/java/com/google/gson/regression/OSGiTest.java index a4a6238a10..29ff39b8dd 100644 --- a/gson/src/test/java/com/google/gson/regression/OSGiTest.java +++ b/gson/src/test/java/com/google/gson/regression/OSGiTest.java @@ -34,10 +34,9 @@ public void testComGoogleGsonAnnotationsPackage() throws Exception { Manifest mf = findManifest("com.google.gson"); String importPkg = mf.getMainAttributes().getValue("Import-Package"); assertWithMessage("Import-Package statement is there").that(importPkg).isNotNull(); - assertSubstring( - "There should be com.google.gson.annotations dependency", - importPkg, - "com.google.gson.annotations"); + assertWithMessage("There should be com.google.gson.annotations dependency") + .that(importPkg) + .contains("com.google.gson.annotations"); } @Test @@ -47,7 +46,7 @@ public void testSunMiscImportPackage() throws Exception { assertWithMessage("Import-Package statement is there").that(importPkg).isNotNull(); for (String dep : Splitter.on(',').split(importPkg)) { if (dep.contains("sun.misc")) { - assertSubstring("sun.misc import is optional", dep, "resolution:=optional"); + assertWithMessage("sun.misc import is optional").that(dep).contains("resolution:=optional"); return; } } @@ -69,11 +68,4 @@ private Manifest findManifest(String pkg) throws IOException { fail("Cannot find " + pkg + " OSGi bundle manifest among: " + urls); return null; } - - private static void assertSubstring(String msg, String wholeText, String subString) { - if (wholeText.contains(subString)) { - return; - } - fail(msg + ". Expecting " + subString + " but was: " + wholeText); - } } diff --git a/gson/src/test/java/com/google/gson/stream/JsonReaderTest.java b/gson/src/test/java/com/google/gson/stream/JsonReaderTest.java index d614e5362b..982852e3cf 100644 --- a/gson/src/test/java/com/google/gson/stream/JsonReaderTest.java +++ b/gson/src/test/java/com/google/gson/stream/JsonReaderTest.java @@ -27,7 +27,6 @@ import static com.google.gson.stream.JsonToken.NUMBER; import static com.google.gson.stream.JsonToken.STRING; import static org.junit.Assert.assertThrows; -import static org.junit.Assert.fail; import com.google.gson.Strictness; import java.io.EOFException; @@ -449,40 +448,24 @@ public void testInvalidJsonInput() throws IOException { JsonReader reader = new JsonReader(reader(json)); reader.beginObject(); - try { - reader.nextName(); - fail(); - } catch (MalformedJsonException expected) { - assertThat(expected) - .hasMessageThat() - .isEqualTo( - "Invalid escape sequence at line 2 column 8 path $.\n" - + "See https://github.com/google/gson/blob/main/Troubleshooting.md#malformed-json"); - } + var e = assertThrows(MalformedJsonException.class, () -> reader.nextName()); + assertThat(e) + .hasMessageThat() + .isEqualTo( + "Invalid escape sequence at line 2 column 8 path $.\n" + + "See https://github.com/google/gson/blob/main/Troubleshooting.md#malformed-json"); } @SuppressWarnings("unused") @Test public void testNulls() { - try { - new JsonReader(null); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> new JsonReader(null)); } @Test public void testEmptyString() throws IOException { - try { - new JsonReader(reader("")).beginArray(); - fail(); - } catch (EOFException expected) { - } - try { - new JsonReader(reader("")).beginObject(); - fail(); - } catch (EOFException expected) { - } + assertThrows(EOFException.class, () -> new JsonReader(reader("")).beginArray()); + assertThrows(EOFException.class, () -> new JsonReader(reader("")).beginObject()); } @Test @@ -584,16 +567,12 @@ public void testUnescapingInvalidCharacters() throws IOException { String json = "[\"\\u000g\"]"; JsonReader reader = new JsonReader(reader(json)); reader.beginArray(); - try { - reader.nextString(); - fail(); - } catch (MalformedJsonException expected) { - assertThat(expected) - .hasMessageThat() - .isEqualTo( - "Malformed Unicode escape \\u000g at line 1 column 5 path $[0]\n" - + "See https://github.com/google/gson/blob/main/Troubleshooting.md#malformed-json"); - } + var e = assertThrows(MalformedJsonException.class, () -> reader.nextString()); + assertThat(e) + .hasMessageThat() + .isEqualTo( + "Malformed Unicode escape \\u000g at line 1 column 5 path $[0]\n" + + "See https://github.com/google/gson/blob/main/Troubleshooting.md#malformed-json"); } @Test @@ -601,16 +580,12 @@ public void testUnescapingTruncatedCharacters() throws IOException { String json = "[\"\\u000"; JsonReader reader = new JsonReader(reader(json)); reader.beginArray(); - try { - reader.nextString(); - fail(); - } catch (MalformedJsonException expected) { - assertThat(expected) - .hasMessageThat() - .isEqualTo( - "Unterminated escape sequence at line 1 column 5 path $[0]\n" - + "See https://github.com/google/gson/blob/main/Troubleshooting.md#malformed-json"); - } + var e = assertThrows(MalformedJsonException.class, () -> reader.nextString()); + assertThat(e) + .hasMessageThat() + .isEqualTo( + "Unterminated escape sequence at line 1 column 5 path $[0]\n" + + "See https://github.com/google/gson/blob/main/Troubleshooting.md#malformed-json"); } @Test @@ -618,16 +593,12 @@ public void testUnescapingTruncatedSequence() throws IOException { String json = "[\"\\"; JsonReader reader = new JsonReader(reader(json)); reader.beginArray(); - try { - reader.nextString(); - fail(); - } catch (MalformedJsonException expected) { - assertThat(expected) - .hasMessageThat() - .isEqualTo( - "Unterminated escape sequence at line 1 column 4 path $[0]\n" - + "See https://github.com/google/gson/blob/main/Troubleshooting.md#malformed-json"); - } + var e = assertThrows(MalformedJsonException.class, () -> reader.nextString()); + assertThat(e) + .hasMessageThat() + .isEqualTo( + "Unterminated escape sequence at line 1 column 4 path $[0]\n" + + "See https://github.com/google/gson/blob/main/Troubleshooting.md#malformed-json"); } @Test @@ -689,12 +660,8 @@ public void testStrictNonFiniteDoubles() throws IOException { String json = "[NaN]"; JsonReader reader = new JsonReader(reader(json)); reader.beginArray(); - try { - reader.nextDouble(); - fail(); - } catch (MalformedJsonException expected) { - assertStrictError(expected, "line 1 column 2 path $[0]"); - } + var e = assertThrows(MalformedJsonException.class, () -> reader.nextDouble()); + assertStrictError(e, "line 1 column 2 path $[0]"); } @Test @@ -702,16 +669,12 @@ public void testStrictQuotedNonFiniteDoubles() throws IOException { String json = "[\"NaN\"]"; JsonReader reader = new JsonReader(reader(json)); reader.beginArray(); - try { - reader.nextDouble(); - fail(); - } catch (MalformedJsonException expected) { - assertThat(expected) - .hasMessageThat() - .isEqualTo( - "JSON forbids NaN and infinities: NaN at line 1 column 7 path $[0]\n" - + "See https://github.com/google/gson/blob/main/Troubleshooting.md#malformed-json"); - } + var e = assertThrows(MalformedJsonException.class, () -> reader.nextDouble()); + assertThat(e) + .hasMessageThat() + .isEqualTo( + "JSON forbids NaN and infinities: NaN at line 1 column 7 path $[0]\n" + + "See https://github.com/google/gson/blob/main/Troubleshooting.md#malformed-json"); } @Test @@ -743,12 +706,8 @@ public void testStrictNonFiniteDoublesWithSkipValue() throws IOException { String json = "[NaN]"; JsonReader reader = new JsonReader(reader(json)); reader.beginArray(); - try { - reader.skipValue(); - fail(); - } catch (MalformedJsonException expected) { - assertStrictError(expected, "line 1 column 2 path $[0]"); - } + var e = assertThrows(MalformedJsonException.class, () -> reader.skipValue()); + assertStrictError(e, "line 1 column 2 path $[0]"); } @Test @@ -766,18 +725,13 @@ public void testLongs() throws IOException { assertThat(reader.nextLong()).isEqualTo(-1L); assertThat(reader.nextInt()).isEqualTo(-1); assertThat(reader.nextDouble()).isEqualTo(-1.0); - try { - reader.nextInt(); - fail(); - } catch (NumberFormatException expected) { - } + + assertThrows(NumberFormatException.class, () -> reader.nextInt()); assertThat(reader.nextLong()).isEqualTo(Long.MIN_VALUE); - try { - reader.nextInt(); - fail(); - } catch (NumberFormatException expected) { - } + + assertThrows(NumberFormatException.class, () -> reader.nextInt()); assertThat(reader.nextLong()).isEqualTo(Long.MAX_VALUE); + reader.endArray(); assertThat(reader.peek()).isEqualTo(JsonToken.END_DOCUMENT); } @@ -790,30 +744,19 @@ public void testNumberWithOctalPrefix() throws IOException { String json = "[01]"; JsonReader reader = new JsonReader(reader(json)); reader.beginArray(); - try { - reader.peek(); - fail(); - } catch (MalformedJsonException expected) { - assertStrictError(expected, "line 1 column 2 path $[0]"); - } - try { - reader.nextInt(); - fail(); - } catch (MalformedJsonException expected) { - assertStrictError(expected, "TODO"); - } - try { - reader.nextLong(); - fail(); - } catch (MalformedJsonException expected) { - assertStrictError(expected, "TODO"); - } - try { - reader.nextDouble(); - fail(); - } catch (MalformedJsonException expected) { - assertStrictError(expected, "TODO"); - } + + var e = assertThrows(MalformedJsonException.class, () -> reader.peek()); + assertStrictError(e, "line 1 column 2 path $[0]"); + + e = assertThrows(MalformedJsonException.class, () -> reader.nextInt()); + assertStrictError(e, "TODO"); + + e = assertThrows(MalformedJsonException.class, () -> reader.nextLong()); + assertStrictError(e, "TODO"); + + e = assertThrows(MalformedJsonException.class, () -> reader.nextDouble()); + assertStrictError(e, "TODO"); + assertThat(reader.nextString()).isEqualTo("01"); reader.endArray(); assertThat(reader.peek()).isEqualTo(JsonToken.END_DOCUMENT); @@ -835,12 +778,10 @@ public void testPeekingUnquotedStringsPrefixedWithBooleans() throws IOException reader.setStrictness(Strictness.LENIENT); reader.beginArray(); assertThat(reader.peek()).isEqualTo(STRING); - try { - reader.nextBoolean(); - fail(); - } catch (IllegalStateException expected) { - assertUnexpectedStructureError(expected, "a boolean", "STRING", "line 1 column 2 path $[0]"); - } + + var e = assertThrows(IllegalStateException.class, () -> reader.nextBoolean()); + assertUnexpectedStructureError(e, "a boolean", "STRING", "line 1 column 2 path $[0]"); + assertThat(reader.nextString()).isEqualTo("truey"); reader.endArray(); } @@ -897,14 +838,14 @@ private static void assertNotANumber(String s) throws IOException { assertThat(reader.nextString()).isEqualTo(s); JsonReader strictReader = new JsonReader(reader(s)); - try { - strictReader.nextDouble(); - fail("Should have failed reading " + s + " as double"); - } catch (MalformedJsonException e) { - assertThat(e) - .hasMessageThat() - .startsWith("Use JsonReader.setStrictness(Strictness.LENIENT) to accept malformed JSON"); - } + var e = + assertThrows( + "Should have failed reading " + s + " as double", + MalformedJsonException.class, + () -> strictReader.nextDouble()); + assertThat(e) + .hasMessageThat() + .startsWith("Use JsonReader.setStrictness(Strictness.LENIENT) to accept malformed JSON"); } @Test @@ -913,11 +854,8 @@ public void testPeekingUnquotedStringsPrefixedWithIntegers() throws IOException reader.setStrictness(Strictness.LENIENT); reader.beginArray(); assertThat(reader.peek()).isEqualTo(STRING); - try { - reader.nextInt(); - fail(); - } catch (NumberFormatException expected) { - } + + assertThrows(NumberFormatException.class, () -> reader.nextInt()); assertThat(reader.nextString()).isEqualTo("12.34e5x"); } @@ -945,11 +883,7 @@ public void testLongLargerThanMaxLongThatWrapsAround() throws IOException { reader.setStrictness(Strictness.LENIENT); reader.beginArray(); assertThat(reader.peek()).isEqualTo(NUMBER); - try { - reader.nextLong(); - fail(); - } catch (NumberFormatException expected) { - } + assertThrows(NumberFormatException.class, () -> reader.nextLong()); } @Test @@ -958,11 +892,7 @@ public void testLongLargerThanMinLongThatWrapsAround() throws IOException { reader.setStrictness(Strictness.LENIENT); reader.beginArray(); assertThat(reader.peek()).isEqualTo(NUMBER); - try { - reader.nextLong(); - fail(); - } catch (NumberFormatException expected) { - } + assertThrows(NumberFormatException.class, () -> reader.nextLong()); } /** Issue 1053, negative zero. */ @@ -977,7 +907,7 @@ public void testNegativeZero() throws Exception { /** * This test fails because there's no double for 9223372036854775808, and our long parsing uses - * Double.parseDouble() for fractional values. + * {@link Double#parseDouble(String)} for fractional values. */ @Test @Ignore @@ -986,11 +916,7 @@ public void testPeekLargerThanLongMaxValue() throws IOException { reader.setStrictness(Strictness.LENIENT); reader.beginArray(); assertThat(reader.peek()).isEqualTo(NUMBER); - try { - reader.nextLong(); - fail(); - } catch (NumberFormatException e) { - } + assertThrows(NumberFormatException.class, () -> reader.nextLong()); } /** @@ -1006,11 +932,7 @@ public void testPeekLargerThanLongMinValue() throws IOException { reader.setStrictness(Strictness.LENIENT); reader.beginArray(); assertThat(reader.peek()).isEqualTo(NUMBER); - try { - reader.nextLong(); - fail(); - } catch (NumberFormatException expected) { - } + assertThrows(NumberFormatException.class, () -> reader.nextLong()); assertThat(reader.nextDouble()).isEqualTo(d); } @@ -1036,11 +958,7 @@ public void testPeekMuchLargerThanLongMinValue() throws IOException { reader.setStrictness(Strictness.LENIENT); reader.beginArray(); assertThat(reader.peek()).isEqualTo(NUMBER); - try { - reader.nextLong(); - fail(); - } catch (NumberFormatException expected) { - } + assertThrows(NumberFormatException.class, () -> reader.nextLong()); assertThat(reader.nextDouble()).isEqualTo(d); } @@ -1072,16 +990,12 @@ public void testMissingValue() throws IOException { JsonReader reader = new JsonReader(reader("{\"a\":}")); reader.beginObject(); assertThat(reader.nextName()).isEqualTo("a"); - try { - reader.nextString(); - fail(); - } catch (MalformedJsonException expected) { - assertThat(expected) - .hasMessageThat() - .isEqualTo( - "Expected value at line 1 column 6 path $.a\n" - + "See https://github.com/google/gson/blob/main/Troubleshooting.md#malformed-json"); - } + var e = assertThrows(MalformedJsonException.class, () -> reader.nextString()); + assertThat(e) + .hasMessageThat() + .isEqualTo( + "Expected value at line 1 column 6 path $.a\n" + + "See https://github.com/google/gson/blob/main/Troubleshooting.md#malformed-json"); } @Test @@ -1090,11 +1004,7 @@ public void testPrematureEndOfInput() throws IOException { reader.beginObject(); assertThat(reader.nextName()).isEqualTo("a"); assertThat(reader.nextBoolean()).isTrue(); - try { - reader.nextName(); - fail(); - } catch (EOFException expected) { - } + assertThrows(EOFException.class, () -> reader.nextName()); } @Test @@ -1102,107 +1012,62 @@ public void testPrematurelyClosed() throws IOException { JsonReader reader = new JsonReader(reader("{\"a\":[]}")); reader.beginObject(); reader.close(); - try { - reader.nextName(); - fail(); - } catch (IllegalStateException expected) { - assertThat(expected).hasMessageThat().isEqualTo("JsonReader is closed"); - } + var e = assertThrows(IllegalStateException.class, () -> reader.nextName()); + assertThat(e).hasMessageThat().isEqualTo("JsonReader is closed"); - reader = new JsonReader(reader("{\"a\":[]}")); - reader.close(); - try { - reader.beginObject(); - fail(); - } catch (IllegalStateException expected) { - assertThat(expected).hasMessageThat().isEqualTo("JsonReader is closed"); - } + JsonReader reader2 = new JsonReader(reader("{\"a\":[]}")); + reader2.close(); + e = assertThrows(IllegalStateException.class, () -> reader2.beginObject()); + assertThat(e).hasMessageThat().isEqualTo("JsonReader is closed"); - reader = new JsonReader(reader("{\"a\":true}")); - reader.beginObject(); - String unused1 = reader.nextName(); - JsonToken unused2 = reader.peek(); - reader.close(); - try { - reader.nextBoolean(); - fail(); - } catch (IllegalStateException expected) { - assertThat(expected).hasMessageThat().isEqualTo("JsonReader is closed"); - } + JsonReader reader3 = new JsonReader(reader("{\"a\":true}")); + reader3.beginObject(); + String unused1 = reader3.nextName(); + JsonToken unused2 = reader3.peek(); + reader3.close(); + e = assertThrows(IllegalStateException.class, () -> reader3.nextBoolean()); + assertThat(e).hasMessageThat().isEqualTo("JsonReader is closed"); } @Test public void testNextFailuresDoNotAdvance() throws IOException { JsonReader reader = new JsonReader(reader("{\"a\":true}")); reader.beginObject(); - try { - String unused = reader.nextString(); - fail(); - } catch (IllegalStateException expected) { - assertUnexpectedStructureError(expected, "a string", "NAME", "line 1 column 3 path $."); - } + + var e = assertThrows(IllegalStateException.class, () -> reader.nextString()); + assertUnexpectedStructureError(e, "a string", "NAME", "line 1 column 3 path $."); + assertThat(reader.nextName()).isEqualTo("a"); - try { - String unused = reader.nextName(); - fail(); - } catch (IllegalStateException expected) { - assertUnexpectedStructureError(expected, "a name", "BOOLEAN", "line 1 column 10 path $.a"); - } - try { - reader.beginArray(); - fail(); - } catch (IllegalStateException expected) { - assertUnexpectedStructureError( - expected, "BEGIN_ARRAY", "BOOLEAN", "line 1 column 10 path $.a"); - } - try { - reader.endArray(); - fail(); - } catch (IllegalStateException expected) { - assertUnexpectedStructureError(expected, "END_ARRAY", "BOOLEAN", "line 1 column 10 path $.a"); - } - try { - reader.beginObject(); - fail(); - } catch (IllegalStateException expected) { - assertUnexpectedStructureError( - expected, "BEGIN_OBJECT", "BOOLEAN", "line 1 column 10 path $.a"); - } - try { - reader.endObject(); - fail(); - } catch (IllegalStateException expected) { - assertUnexpectedStructureError( - expected, "END_OBJECT", "BOOLEAN", "line 1 column 10 path $.a"); - } + + e = assertThrows(IllegalStateException.class, () -> reader.nextName()); + assertUnexpectedStructureError(e, "a name", "BOOLEAN", "line 1 column 10 path $.a"); + + e = assertThrows(IllegalStateException.class, () -> reader.beginArray()); + assertUnexpectedStructureError(e, "BEGIN_ARRAY", "BOOLEAN", "line 1 column 10 path $.a"); + + e = assertThrows(IllegalStateException.class, () -> reader.endArray()); + assertUnexpectedStructureError(e, "END_ARRAY", "BOOLEAN", "line 1 column 10 path $.a"); + + e = assertThrows(IllegalStateException.class, () -> reader.beginObject()); + assertUnexpectedStructureError(e, "BEGIN_OBJECT", "BOOLEAN", "line 1 column 10 path $.a"); + + e = assertThrows(IllegalStateException.class, () -> reader.endObject()); + assertUnexpectedStructureError(e, "END_OBJECT", "BOOLEAN", "line 1 column 10 path $.a"); + assertThat(reader.nextBoolean()).isTrue(); - try { - reader.nextString(); - fail(); - } catch (IllegalStateException expected) { - assertUnexpectedStructureError( - expected, "a string", "END_OBJECT", "line 1 column 11 path $.a"); - } - try { - reader.nextName(); - fail(); - } catch (IllegalStateException expected) { - assertUnexpectedStructureError(expected, "a name", "END_OBJECT", "line 1 column 11 path $.a"); - } - try { - reader.beginArray(); - fail(); - } catch (IllegalStateException expected) { - assertUnexpectedStructureError( - expected, "BEGIN_ARRAY", "END_OBJECT", "line 1 column 11 path $.a"); - } - try { - reader.endArray(); - fail(); - } catch (IllegalStateException expected) { - assertUnexpectedStructureError( - expected, "END_ARRAY", "END_OBJECT", "line 1 column 11 path $.a"); - } + + e = assertThrows(IllegalStateException.class, () -> reader.nextString()); + assertUnexpectedStructureError(e, "a string", "END_OBJECT", "line 1 column 11 path $.a"); + + e = assertThrows(IllegalStateException.class, () -> reader.nextName()); + assertUnexpectedStructureError(e, "a name", "END_OBJECT", "line 1 column 11 path $.a"); + + e = assertThrows(IllegalStateException.class, () -> reader.beginArray()); + assertUnexpectedStructureError(e, "BEGIN_ARRAY", "END_OBJECT", "line 1 column 11 path $.a"); + + e = assertThrows(IllegalStateException.class, () -> reader.endArray()); + assertUnexpectedStructureError(e, "END_ARRAY", "END_OBJECT", "line 1 column 11 path $.a"); + reader.endObject(); assertThat(reader.peek()).isEqualTo(JsonToken.END_DOCUMENT); reader.close(); @@ -1212,11 +1077,7 @@ public void testNextFailuresDoNotAdvance() throws IOException { public void testIntegerMismatchFailuresDoNotAdvance() throws IOException { JsonReader reader = new JsonReader(reader("[1.5]")); reader.beginArray(); - try { - reader.nextInt(); - fail(); - } catch (NumberFormatException expected) { - } + assertThrows(NumberFormatException.class, () -> reader.nextInt()); assertThat(reader.nextDouble()).isEqualTo(1.5d); reader.endArray(); } @@ -1225,24 +1086,16 @@ public void testIntegerMismatchFailuresDoNotAdvance() throws IOException { public void testStringNullIsNotNull() throws IOException { JsonReader reader = new JsonReader(reader("[\"null\"]")); reader.beginArray(); - try { - reader.nextNull(); - fail(); - } catch (IllegalStateException expected) { - assertUnexpectedStructureError(expected, "null", "STRING", "line 1 column 3 path $[0]"); - } + var e = assertThrows(IllegalStateException.class, () -> reader.nextNull()); + assertUnexpectedStructureError(e, "null", "STRING", "line 1 column 3 path $[0]"); } @Test public void testNullLiteralIsNotAString() throws IOException { JsonReader reader = new JsonReader(reader("[null]")); reader.beginArray(); - try { - reader.nextString(); - fail(); - } catch (IllegalStateException expected) { - assertUnexpectedStructureError(expected, "a string", "NULL", "line 1 column 6 path $[0]"); - } + var e = assertThrows(IllegalStateException.class, () -> reader.nextString()); + assertUnexpectedStructureError(e, "a string", "NULL", "line 1 column 6 path $[0]"); } @Test @@ -1250,22 +1103,16 @@ public void testStrictNameValueSeparator() throws IOException { JsonReader reader = new JsonReader(reader("{\"a\"=true}")); reader.beginObject(); assertThat(reader.nextName()).isEqualTo("a"); - try { - reader.nextBoolean(); - fail(); - } catch (MalformedJsonException expected) { - assertStrictError(expected, "line 1 column 6 path $.a"); - } + var e = assertThrows(MalformedJsonException.class, () -> reader.nextBoolean()); + assertStrictError(e, "line 1 column 6 path $.a"); - reader = new JsonReader(reader("{\"a\"=>true}")); - reader.beginObject(); - assertThat(reader.nextName()).isEqualTo("a"); - try { - reader.nextBoolean(); - fail(); - } catch (MalformedJsonException expected) { - assertStrictError(expected, "line 1 column 6 path $.a"); - } + JsonReader reader2 = new JsonReader(reader("{\"a\"=>true}")); + reader2.beginObject(); + + assertThat(reader2.nextName()).isEqualTo("a"); + + e = assertThrows(MalformedJsonException.class, () -> reader2.nextBoolean()); + assertStrictError(e, "line 1 column 6 path $.a"); } @Test @@ -1288,22 +1135,15 @@ public void testStrictNameValueSeparatorWithSkipValue() throws IOException { JsonReader reader = new JsonReader(reader("{\"a\"=true}")); reader.beginObject(); assertThat(reader.nextName()).isEqualTo("a"); - try { - reader.skipValue(); - fail(); - } catch (MalformedJsonException expected) { - assertStrictError(expected, "line 1 column 6 path $.a"); - } + var e = assertThrows(MalformedJsonException.class, () -> reader.skipValue()); + assertStrictError(e, "line 1 column 6 path $.a"); - reader = new JsonReader(reader("{\"a\"=>true}")); - reader.beginObject(); - assertThat(reader.nextName()).isEqualTo("a"); - try { - reader.skipValue(); - fail(); - } catch (MalformedJsonException expected) { - assertStrictError(expected, "line 1 column 6 path $.a"); - } + JsonReader reader2 = new JsonReader(reader("{\"a\"=>true}")); + reader2.beginObject(); + assertThat(reader2.nextName()).isEqualTo("a"); + + e = assertThrows(MalformedJsonException.class, () -> reader2.skipValue()); + assertStrictError(e, "line 1 column 6 path $.a"); } @Test @@ -1330,30 +1170,18 @@ public void testCommentsInStringValue() throws Exception { public void testStrictComments() throws IOException { JsonReader reader = new JsonReader(reader("[// comment \n true]")); reader.beginArray(); - try { - reader.nextBoolean(); - fail(); - } catch (MalformedJsonException expected) { - assertStrictError(expected, "line 1 column 3 path $[0]"); - } + var e = assertThrows(MalformedJsonException.class, () -> reader.nextBoolean()); + assertStrictError(e, "line 1 column 3 path $[0]"); - reader = new JsonReader(reader("[# comment \n true]")); - reader.beginArray(); - try { - reader.nextBoolean(); - fail(); - } catch (MalformedJsonException expected) { - assertStrictError(expected, "line 1 column 3 path $[0]"); - } + JsonReader reader2 = new JsonReader(reader("[# comment \n true]")); + reader2.beginArray(); + e = assertThrows(MalformedJsonException.class, () -> reader2.nextBoolean()); + assertStrictError(e, "line 1 column 3 path $[0]"); - reader = new JsonReader(reader("[/* comment */ true]")); - reader.beginArray(); - try { - reader.nextBoolean(); - fail(); - } catch (MalformedJsonException expected) { - assertStrictError(expected, "line 1 column 3 path $[0]"); - } + JsonReader reader3 = new JsonReader(reader("[/* comment */ true]")); + reader3.beginArray(); + e = assertThrows(MalformedJsonException.class, () -> reader3.nextBoolean()); + assertStrictError(e, "line 1 column 3 path $[0]"); } @Test @@ -1378,42 +1206,26 @@ public void testLenientComments() throws IOException { public void testStrictCommentsWithSkipValue() throws IOException { JsonReader reader = new JsonReader(reader("[// comment \n true]")); reader.beginArray(); - try { - reader.skipValue(); - fail(); - } catch (MalformedJsonException expected) { - assertStrictError(expected, "line 1 column 3 path $[0]"); - } + var e = assertThrows(MalformedJsonException.class, () -> reader.skipValue()); + assertStrictError(e, "line 1 column 3 path $[0]"); - reader = new JsonReader(reader("[# comment \n true]")); - reader.beginArray(); - try { - reader.skipValue(); - fail(); - } catch (MalformedJsonException expected) { - assertStrictError(expected, "line 1 column 3 path $[0]"); - } + JsonReader reader2 = new JsonReader(reader("[# comment \n true]")); + reader2.beginArray(); + e = assertThrows(MalformedJsonException.class, () -> reader2.skipValue()); + assertStrictError(e, "line 1 column 3 path $[0]"); - reader = new JsonReader(reader("[/* comment */ true]")); - reader.beginArray(); - try { - reader.skipValue(); - fail(); - } catch (MalformedJsonException expected) { - assertStrictError(expected, "line 1 column 3 path $[0]"); - } + JsonReader reader3 = new JsonReader(reader("[/* comment */ true]")); + reader3.beginArray(); + e = assertThrows(MalformedJsonException.class, () -> reader3.skipValue()); + assertStrictError(e, "line 1 column 3 path $[0]"); } @Test public void testStrictUnquotedNames() throws IOException { JsonReader reader = new JsonReader(reader("{a:true}")); reader.beginObject(); - try { - reader.nextName(); - fail(); - } catch (MalformedJsonException expected) { - assertStrictError(expected, "line 1 column 3 path $."); - } + var e = assertThrows(MalformedJsonException.class, () -> reader.nextName()); + assertStrictError(e, "line 1 column 3 path $."); } @Test @@ -1428,24 +1240,16 @@ public void testLenientUnquotedNames() throws IOException { public void testStrictUnquotedNamesWithSkipValue() throws IOException { JsonReader reader = new JsonReader(reader("{a:true}")); reader.beginObject(); - try { - reader.skipValue(); - fail(); - } catch (MalformedJsonException expected) { - assertStrictError(expected, "line 1 column 3 path $."); - } + var e = assertThrows(MalformedJsonException.class, () -> reader.skipValue()); + assertStrictError(e, "line 1 column 3 path $."); } @Test public void testStrictSingleQuotedNames() throws IOException { JsonReader reader = new JsonReader(reader("{'a':true}")); reader.beginObject(); - try { - reader.nextName(); - fail(); - } catch (MalformedJsonException expected) { - assertStrictError(expected, "line 1 column 3 path $."); - } + var e = assertThrows(MalformedJsonException.class, () -> reader.nextName()); + assertStrictError(e, "line 1 column 3 path $."); } @Test @@ -1460,36 +1264,24 @@ public void testLenientSingleQuotedNames() throws IOException { public void testStrictSingleQuotedNamesWithSkipValue() throws IOException { JsonReader reader = new JsonReader(reader("{'a':true}")); reader.beginObject(); - try { - reader.skipValue(); - fail(); - } catch (MalformedJsonException expected) { - assertStrictError(expected, "line 1 column 3 path $."); - } + var e = assertThrows(MalformedJsonException.class, () -> reader.skipValue()); + assertStrictError(e, "line 1 column 3 path $."); } @Test public void testStrictUnquotedStrings() throws IOException { JsonReader reader = new JsonReader(reader("[a]")); reader.beginArray(); - try { - reader.nextString(); - fail(); - } catch (MalformedJsonException expected) { - assertStrictError(expected, "line 1 column 2 path $[0]"); - } + var e = assertThrows(MalformedJsonException.class, () -> reader.nextString()); + assertStrictError(e, "line 1 column 2 path $[0]"); } @Test public void testStrictUnquotedStringsWithSkipValue() throws IOException { JsonReader reader = new JsonReader(reader("[a]")); reader.beginArray(); - try { - reader.skipValue(); - fail(); - } catch (MalformedJsonException expected) { - assertStrictError(expected, "line 1 column 2 path $[0]"); - } + var e = assertThrows(MalformedJsonException.class, () -> reader.skipValue()); + assertStrictError(e, "line 1 column 2 path $[0]"); } @Test @@ -1504,12 +1296,8 @@ public void testLenientUnquotedStrings() throws IOException { public void testStrictSingleQuotedStrings() throws IOException { JsonReader reader = new JsonReader(reader("['a']")); reader.beginArray(); - try { - reader.nextString(); - fail(); - } catch (MalformedJsonException expected) { - assertStrictError(expected, "line 1 column 3 path $[0]"); - } + var e = assertThrows(MalformedJsonException.class, () -> reader.nextString()); + assertStrictError(e, "line 1 column 3 path $[0]"); } @Test @@ -1524,24 +1312,16 @@ public void testLenientSingleQuotedStrings() throws IOException { public void testStrictSingleQuotedStringsWithSkipValue() throws IOException { JsonReader reader = new JsonReader(reader("['a']")); reader.beginArray(); - try { - reader.skipValue(); - fail(); - } catch (MalformedJsonException expected) { - assertStrictError(expected, "line 1 column 3 path $[0]"); - } + var e = assertThrows(MalformedJsonException.class, () -> reader.skipValue()); + assertStrictError(e, "line 1 column 3 path $[0]"); } @Test public void testStrictSemicolonDelimitedArray() throws IOException { JsonReader reader = new JsonReader(reader("[true;true]")); reader.beginArray(); - try { - boolean unused = reader.nextBoolean(); - fail(); - } catch (MalformedJsonException expected) { - assertStrictError(expected, "line 1 column 2 path $[0]"); - } + var e = assertThrows(MalformedJsonException.class, () -> reader.nextBoolean()); + assertStrictError(e, "line 1 column 2 path $[0]"); } @Test @@ -1557,12 +1337,8 @@ public void testLenientSemicolonDelimitedArray() throws IOException { public void testStrictSemicolonDelimitedArrayWithSkipValue() throws IOException { JsonReader reader = new JsonReader(reader("[true;true]")); reader.beginArray(); - try { - reader.skipValue(); - fail(); - } catch (MalformedJsonException expected) { - assertStrictError(expected, "line 1 column 2 path $[0]"); - } + var e = assertThrows(MalformedJsonException.class, () -> reader.skipValue()); + assertStrictError(e, "line 1 column 2 path $[0]"); } @Test @@ -1570,12 +1346,8 @@ public void testStrictSemicolonDelimitedNameValuePair() throws IOException { JsonReader reader = new JsonReader(reader("{\"a\":true;\"b\":true}")); reader.beginObject(); assertThat(reader.nextName()).isEqualTo("a"); - try { - boolean unused = reader.nextBoolean(); - fail(); - } catch (MalformedJsonException expected) { - assertStrictError(expected, "line 1 column 6 path $.a"); - } + var e = assertThrows(MalformedJsonException.class, () -> reader.nextBoolean()); + assertStrictError(e, "line 1 column 6 path $.a"); } @Test @@ -1593,12 +1365,8 @@ public void testStrictSemicolonDelimitedNameValuePairWithSkipValue() throws IOEx JsonReader reader = new JsonReader(reader("{\"a\":true;\"b\":true}")); reader.beginObject(); assertThat(reader.nextName()).isEqualTo("a"); - try { - reader.skipValue(); - fail(); - } catch (MalformedJsonException expected) { - assertStrictError(expected, "line 1 column 6 path $.a"); - } + var e = assertThrows(MalformedJsonException.class, () -> reader.skipValue()); + assertStrictError(e, "line 1 column 6 path $.a"); } @Test @@ -1606,40 +1374,24 @@ public void testStrictUnnecessaryArraySeparators() throws IOException { JsonReader reader = new JsonReader(reader("[true,,true]")); reader.beginArray(); assertThat(reader.nextBoolean()).isTrue(); - try { - reader.nextNull(); - fail(); - } catch (MalformedJsonException expected) { - assertStrictError(expected, "line 1 column 8 path $[1]"); - } + var e = assertThrows(MalformedJsonException.class, () -> reader.nextNull()); + assertStrictError(e, "line 1 column 8 path $[1]"); - reader = new JsonReader(reader("[,true]")); - reader.beginArray(); - try { - reader.nextNull(); - fail(); - } catch (MalformedJsonException expected) { - assertStrictError(expected, "line 1 column 3 path $[0]"); - } + JsonReader reader2 = new JsonReader(reader("[,true]")); + reader2.beginArray(); + e = assertThrows(MalformedJsonException.class, () -> reader2.nextNull()); + assertStrictError(e, "line 1 column 3 path $[0]"); - reader = new JsonReader(reader("[true,]")); - reader.beginArray(); - assertThat(reader.nextBoolean()).isTrue(); - try { - reader.nextNull(); - fail(); - } catch (MalformedJsonException expected) { - assertStrictError(expected, "line 1 column 8 path $[1]"); - } + JsonReader reader3 = new JsonReader(reader("[true,]")); + reader3.beginArray(); + assertThat(reader3.nextBoolean()).isTrue(); + e = assertThrows(MalformedJsonException.class, () -> reader3.nextNull()); + assertStrictError(e, "line 1 column 8 path $[1]"); - reader = new JsonReader(reader("[,]")); - reader.beginArray(); - try { - reader.nextNull(); - fail(); - } catch (MalformedJsonException expected) { - assertStrictError(expected, "line 1 column 3 path $[0]"); - } + JsonReader reader4 = new JsonReader(reader("[,]")); + reader4.beginArray(); + e = assertThrows(MalformedJsonException.class, () -> reader4.nextNull()); + assertStrictError(e, "line 1 column 3 path $[0]"); } @Test @@ -1679,40 +1431,24 @@ public void testStrictUnnecessaryArraySeparatorsWithSkipValue() throws IOExcepti JsonReader reader = new JsonReader(reader("[true,,true]")); reader.beginArray(); assertThat(reader.nextBoolean()).isTrue(); - try { - reader.skipValue(); - fail(); - } catch (MalformedJsonException expected) { - assertStrictError(expected, "line 1 column 8 path $[1]"); - } + var e = assertThrows(MalformedJsonException.class, () -> reader.skipValue()); + assertStrictError(e, "line 1 column 8 path $[1]"); - reader = new JsonReader(reader("[,true]")); - reader.beginArray(); - try { - reader.skipValue(); - fail(); - } catch (MalformedJsonException expected) { - assertStrictError(expected, "line 1 column 3 path $[0]"); - } + JsonReader reader2 = new JsonReader(reader("[,true]")); + reader2.beginArray(); + e = assertThrows(MalformedJsonException.class, () -> reader2.skipValue()); + assertStrictError(e, "line 1 column 3 path $[0]"); - reader = new JsonReader(reader("[true,]")); - reader.beginArray(); - assertThat(reader.nextBoolean()).isTrue(); - try { - reader.skipValue(); - fail(); - } catch (MalformedJsonException expected) { - assertStrictError(expected, "line 1 column 8 path $[1]"); - } + JsonReader reader3 = new JsonReader(reader("[true,]")); + reader3.beginArray(); + assertThat(reader3.nextBoolean()).isTrue(); + e = assertThrows(MalformedJsonException.class, () -> reader3.skipValue()); + assertStrictError(e, "line 1 column 8 path $[1]"); - reader = new JsonReader(reader("[,]")); - reader.beginArray(); - try { - reader.skipValue(); - fail(); - } catch (MalformedJsonException expected) { - assertStrictError(expected, "line 1 column 3 path $[0]"); - } + JsonReader reader4 = new JsonReader(reader("[,]")); + reader4.beginArray(); + e = assertThrows(MalformedJsonException.class, () -> reader4.skipValue()); + assertStrictError(e, "line 1 column 3 path $[0]"); } @Test @@ -1720,12 +1456,8 @@ public void testStrictMultipleTopLevelValues() throws IOException { JsonReader reader = new JsonReader(reader("[] []")); reader.beginArray(); reader.endArray(); - try { - reader.peek(); - fail(); - } catch (MalformedJsonException expected) { - assertStrictError(expected, "line 1 column 5 path $"); - } + var e = assertThrows(MalformedJsonException.class, () -> reader.peek()); + assertStrictError(e, "line 1 column 5 path $"); } @Test @@ -1745,12 +1477,8 @@ public void testStrictMultipleTopLevelValuesWithSkipValue() throws IOException { JsonReader reader = new JsonReader(reader("[] []")); reader.beginArray(); reader.endArray(); - try { - reader.skipValue(); - fail(); - } catch (MalformedJsonException expected) { - assertStrictError(expected, "line 1 column 5 path $"); - } + var e = assertThrows(MalformedJsonException.class, () -> reader.skipValue()); + assertStrictError(e, "line 1 column 5 path $"); } @Test @@ -1791,23 +1519,15 @@ public void testTopLevelValueTypeWithSkipValue() throws IOException { @Test public void testStrictNonExecutePrefix() throws IOException { JsonReader reader = new JsonReader(reader(")]}'\n []")); - try { - reader.beginArray(); - fail(); - } catch (MalformedJsonException expected) { - assertStrictError(expected, "line 1 column 1 path $"); - } + var e = assertThrows(MalformedJsonException.class, () -> reader.beginArray()); + assertStrictError(e, "line 1 column 1 path $"); } @Test public void testStrictNonExecutePrefixWithSkipValue() throws IOException { JsonReader reader = new JsonReader(reader(")]}'\n []")); - try { - reader.skipValue(); - fail(); - } catch (MalformedJsonException expected) { - assertStrictError(expected, "line 1 column 1 path $"); - } + var e = assertThrows(MalformedJsonException.class, () -> reader.skipValue()); + assertStrictError(e, "line 1 column 1 path $"); } @Test @@ -1833,16 +1553,12 @@ public void testLenientPartialNonExecutePrefix() throws IOException { JsonReader reader = new JsonReader(reader(")]}' []")); reader.setStrictness(Strictness.LENIENT); assertThat(reader.nextString()).isEqualTo(")"); - try { - reader.nextString(); - fail(); - } catch (MalformedJsonException expected) { - assertThat(expected) - .hasMessageThat() - .isEqualTo( - "Unexpected value at line 1 column 3 path $\n" - + "See https://github.com/google/gson/blob/main/Troubleshooting.md#malformed-json"); - } + var e = assertThrows(MalformedJsonException.class, () -> reader.nextString()); + assertThat(e) + .hasMessageThat() + .isEqualTo( + "Unexpected value at line 1 column 3 path $\n" + + "See https://github.com/google/gson/blob/main/Troubleshooting.md#malformed-json"); } @Test @@ -1856,12 +1572,8 @@ public void testBomIgnoredAsFirstCharacterOfDocument() throws IOException { public void testBomForbiddenAsOtherCharacterInDocument() throws IOException { JsonReader reader = new JsonReader(reader("[\ufeff]")); reader.beginArray(); - try { - reader.endArray(); - fail(); - } catch (MalformedJsonException expected) { - assertStrictError(expected, "line 1 column 2 path $[0]"); - } + var e = assertThrows(MalformedJsonException.class, () -> reader.endArray()); + assertStrictError(e, "line 1 column 2 path $[0]"); } @SuppressWarnings("UngroupedOverloads") @@ -1922,34 +1634,26 @@ private static void testFailWithPosition(String message, String json) throws IOE reader1.setStrictness(Strictness.LENIENT); reader1.beginArray(); String unused1 = reader1.nextString(); - try { - JsonToken unused2 = reader1.peek(); - fail(); - } catch (MalformedJsonException expected) { - assertThat(expected) - .hasMessageThat() - .isEqualTo( - message - + "\n" - + "See https://github.com/google/gson/blob/main/Troubleshooting.md#malformed-json"); - } + var e = assertThrows(MalformedJsonException.class, () -> reader1.peek()); + assertThat(e) + .hasMessageThat() + .isEqualTo( + message + + "\n" + + "See https://github.com/google/gson/blob/main/Troubleshooting.md#malformed-json"); // Also validate that it works when skipping. JsonReader reader2 = new JsonReader(reader(json)); reader2.setStrictness(Strictness.LENIENT); reader2.beginArray(); reader2.skipValue(); - try { - JsonToken unused3 = reader2.peek(); - fail(); - } catch (MalformedJsonException expected) { - assertThat(expected) - .hasMessageThat() - .isEqualTo( - message - + "\n" - + "See https://github.com/google/gson/blob/main/Troubleshooting.md#malformed-json"); - } + e = assertThrows(MalformedJsonException.class, () -> reader2.peek()); + assertThat(e) + .hasMessageThat() + .isEqualTo( + message + + "\n" + + "See https://github.com/google/gson/blob/main/Troubleshooting.md#malformed-json"); } @Test @@ -1962,28 +1666,20 @@ public void testFailWithPositionDeepPath() throws IOException { reader.beginArray(); int unused3 = reader.nextInt(); int unused4 = reader.nextInt(); - try { - JsonToken unused5 = reader.peek(); - fail(); - } catch (MalformedJsonException expected) { - assertThat(expected) - .hasMessageThat() - .isEqualTo( - "Expected value at line 1 column 14 path $[1].a[2]\n" - + "See https://github.com/google/gson/blob/main/Troubleshooting.md#malformed-json"); - } + var e = assertThrows(MalformedJsonException.class, () -> reader.peek()); + assertThat(e) + .hasMessageThat() + .isEqualTo( + "Expected value at line 1 column 14 path $[1].a[2]\n" + + "See https://github.com/google/gson/blob/main/Troubleshooting.md#malformed-json"); } @Test public void testStrictVeryLongNumber() throws IOException { JsonReader reader = new JsonReader(reader("[0." + repeat('9', 8192) + "]")); reader.beginArray(); - try { - reader.nextDouble(); - fail(); - } catch (MalformedJsonException expected) { - assertStrictError(expected, "line 1 column 2 path $[0]"); - } + var e = assertThrows(MalformedJsonException.class, () -> reader.nextDouble()); + assertStrictError(e, "line 1 column 2 path $[0]"); } @Test @@ -2057,48 +1753,36 @@ public void testDeeplyNestedObjects() throws IOException { public void testStringEndingInSlash() throws IOException { JsonReader reader = new JsonReader(reader("/")); reader.setStrictness(Strictness.LENIENT); - try { - reader.peek(); - fail(); - } catch (MalformedJsonException expected) { - assertThat(expected) - .hasMessageThat() - .isEqualTo( - "Expected value at line 1 column 1 path $\n" - + "See https://github.com/google/gson/blob/main/Troubleshooting.md#malformed-json"); - } + var e = assertThrows(MalformedJsonException.class, () -> reader.peek()); + assertThat(e) + .hasMessageThat() + .isEqualTo( + "Expected value at line 1 column 1 path $\n" + + "See https://github.com/google/gson/blob/main/Troubleshooting.md#malformed-json"); } @Test public void testDocumentWithCommentEndingInSlash() throws IOException { JsonReader reader = new JsonReader(reader("/* foo *//")); reader.setStrictness(Strictness.LENIENT); - try { - reader.peek(); - fail(); - } catch (MalformedJsonException expected) { - assertThat(expected) - .hasMessageThat() - .isEqualTo( - "Expected value at line 1 column 10 path $\n" - + "See https://github.com/google/gson/blob/main/Troubleshooting.md#malformed-json"); - } + var e = assertThrows(MalformedJsonException.class, () -> reader.peek()); + assertThat(e) + .hasMessageThat() + .isEqualTo( + "Expected value at line 1 column 10 path $\n" + + "See https://github.com/google/gson/blob/main/Troubleshooting.md#malformed-json"); } @Test public void testStringWithLeadingSlash() throws IOException { JsonReader reader = new JsonReader(reader("/x")); reader.setStrictness(Strictness.LENIENT); - try { - reader.peek(); - fail(); - } catch (MalformedJsonException expected) { - assertThat(expected) - .hasMessageThat() - .isEqualTo( - "Expected value at line 1 column 1 path $\n" - + "See https://github.com/google/gson/blob/main/Troubleshooting.md#malformed-json"); - } + var e = assertThrows(MalformedJsonException.class, () -> reader.peek()); + assertThat(e) + .hasMessageThat() + .isEqualTo( + "Expected value at line 1 column 1 path $\n" + + "See https://github.com/google/gson/blob/main/Troubleshooting.md#malformed-json"); } @Test @@ -2108,16 +1792,12 @@ public void testUnterminatedObject() throws IOException { reader.beginObject(); assertThat(reader.nextName()).isEqualTo("a"); assertThat(reader.nextString()).isEqualTo("android"); - try { - reader.peek(); - fail(); - } catch (MalformedJsonException expected) { - assertThat(expected) - .hasMessageThat() - .isEqualTo( - "Unterminated object at line 1 column 16 path $.a\n" - + "See https://github.com/google/gson/blob/main/Troubleshooting.md#malformed-json"); - } + var e = assertThrows(MalformedJsonException.class, () -> reader.peek()); + assertThat(e) + .hasMessageThat() + .isEqualTo( + "Unterminated object at line 1 column 16 path $.a\n" + + "See https://github.com/google/gson/blob/main/Troubleshooting.md#malformed-json"); } @Test @@ -2155,11 +1835,7 @@ public void testVeryLongUnterminatedString() throws IOException { reader.setStrictness(Strictness.LENIENT); reader.beginArray(); assertThat(reader.nextString()).isEqualTo(string); - try { - reader.peek(); - fail(); - } catch (EOFException expected) { - } + assertThrows(EOFException.class, () -> reader.peek()); } @Test @@ -2240,16 +1916,12 @@ public void testStrictExtraCommasInMaps() throws IOException { reader.beginObject(); assertThat(reader.nextName()).isEqualTo("a"); assertThat(reader.nextString()).isEqualTo("b"); - try { - reader.peek(); - fail(); - } catch (MalformedJsonException expected) { - assertThat(expected) - .hasMessageThat() - .isEqualTo( - "Expected name at line 1 column 11 path $.a\n" - + "See https://github.com/google/gson/blob/main/Troubleshooting.md#malformed-json"); - } + var e = assertThrows(MalformedJsonException.class, () -> reader.peek()); + assertThat(e) + .hasMessageThat() + .isEqualTo( + "Expected name at line 1 column 11 path $.a\n" + + "See https://github.com/google/gson/blob/main/Troubleshooting.md#malformed-json"); } @Test @@ -2259,16 +1931,12 @@ public void testLenientExtraCommasInMaps() throws IOException { reader.beginObject(); assertThat(reader.nextName()).isEqualTo("a"); assertThat(reader.nextString()).isEqualTo("b"); - try { - reader.peek(); - fail(); - } catch (MalformedJsonException expected) { - assertThat(expected) - .hasMessageThat() - .isEqualTo( - "Expected name at line 1 column 11 path $.a\n" - + "See https://github.com/google/gson/blob/main/Troubleshooting.md#malformed-json"); - } + var e = assertThrows(MalformedJsonException.class, () -> reader.peek()); + assertThat(e) + .hasMessageThat() + .isEqualTo( + "Expected name at line 1 column 11 path $.a\n" + + "See https://github.com/google/gson/blob/main/Troubleshooting.md#malformed-json"); } private static String repeat(char c, int count) { @@ -2333,16 +2001,12 @@ public void testUnterminatedStringFailure() throws IOException { reader.setStrictness(Strictness.LENIENT); reader.beginArray(); assertThat(reader.peek()).isEqualTo(JsonToken.STRING); - try { - reader.nextString(); - fail(); - } catch (MalformedJsonException expected) { - assertThat(expected) - .hasMessageThat() - .isEqualTo( - "Unterminated string at line 1 column 9 path $[0]\n" - + "See https://github.com/google/gson/blob/main/Troubleshooting.md#malformed-json"); - } + var e = assertThrows(MalformedJsonException.class, () -> reader.nextString()); + assertThat(e) + .hasMessageThat() + .isEqualTo( + "Unterminated string at line 1 column 9 path $[0]\n" + + "See https://github.com/google/gson/blob/main/Troubleshooting.md#malformed-json"); } /** Regression test for an issue with buffer filling and consumeNonExecutePrefix. */ @@ -2413,12 +2077,8 @@ private static void assertDocument(String document, Object... expectations) thro reader.nextNull(); } else if (expectation instanceof Class && Exception.class.isAssignableFrom((Class) expectation)) { - try { - reader.peek(); - fail(); - } catch (Exception expected) { - assertThat(expected.getClass()).isEqualTo((Class) expectation); - } + var expected = assertThrows(Exception.class, () -> reader.peek()); + assertThat(expected.getClass()).isEqualTo((Class) expectation); } else { throw new AssertionError("Unsupported expectation value: " + expectation); } diff --git a/gson/src/test/java/com/google/gson/stream/JsonWriterTest.java b/gson/src/test/java/com/google/gson/stream/JsonWriterTest.java index d9435f5600..dd7d8f8db6 100644 --- a/gson/src/test/java/com/google/gson/stream/JsonWriterTest.java +++ b/gson/src/test/java/com/google/gson/stream/JsonWriterTest.java @@ -18,7 +18,6 @@ import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.assertThrows; -import static org.junit.Assert.fail; import com.google.gson.FormattingStyle; import com.google.gson.Strictness; @@ -151,12 +150,8 @@ public void testTwoNames() throws IOException { JsonWriter jsonWriter = new JsonWriter(stringWriter); jsonWriter.beginObject(); jsonWriter.name("a"); - try { - jsonWriter.name("a"); - fail(); - } catch (IllegalStateException expected) { - assertThat(expected).hasMessageThat().isEqualTo("Already wrote a name, expecting a value."); - } + var e = assertThrows(IllegalStateException.class, () -> jsonWriter.name("a")); + assertThat(e).hasMessageThat().isEqualTo("Already wrote a name, expecting a value."); } @Test @@ -165,12 +160,8 @@ public void testNameWithoutValue() throws IOException { JsonWriter jsonWriter = new JsonWriter(stringWriter); jsonWriter.beginObject(); jsonWriter.name("a"); - try { - jsonWriter.endObject(); - fail(); - } catch (IllegalStateException expected) { - assertThat(expected).hasMessageThat().isEqualTo("Dangling name: a"); - } + var e = assertThrows(IllegalStateException.class, () -> jsonWriter.endObject()); + assertThat(e).hasMessageThat().isEqualTo("Dangling name: a"); } @Test @@ -178,12 +169,8 @@ public void testValueWithoutName() throws IOException { StringWriter stringWriter = new StringWriter(); JsonWriter jsonWriter = new JsonWriter(stringWriter); jsonWriter.beginObject(); - try { - jsonWriter.value(true); - fail(); - } catch (IllegalStateException expected) { - assertThat(expected).hasMessageThat().isEqualTo("Nesting problem."); - } + var e = assertThrows(IllegalStateException.class, () -> jsonWriter.value(true)); + assertThat(e).hasMessageThat().isEqualTo("Nesting problem."); } @Test @@ -228,12 +215,8 @@ public void testBadNestingObject() throws IOException { JsonWriter jsonWriter = new JsonWriter(stringWriter); jsonWriter.beginArray(); jsonWriter.beginObject(); - try { - jsonWriter.endArray(); - fail(); - } catch (IllegalStateException expected) { - assertThat(expected).hasMessageThat().isEqualTo("Nesting problem."); - } + var e = assertThrows(IllegalStateException.class, () -> jsonWriter.endArray()); + assertThat(e).hasMessageThat().isEqualTo("Nesting problem."); } @Test @@ -242,12 +225,8 @@ public void testBadNestingArray() throws IOException { JsonWriter jsonWriter = new JsonWriter(stringWriter); jsonWriter.beginArray(); jsonWriter.beginArray(); - try { - jsonWriter.endObject(); - fail(); - } catch (IllegalStateException expected) { - assertThat(expected).hasMessageThat().isEqualTo("Nesting problem."); - } + var e = assertThrows(IllegalStateException.class, () -> jsonWriter.endObject()); + assertThat(e).hasMessageThat().isEqualTo("Nesting problem."); } @Test @@ -255,11 +234,7 @@ public void testNullName() throws IOException { StringWriter stringWriter = new StringWriter(); JsonWriter jsonWriter = new JsonWriter(stringWriter); jsonWriter.beginObject(); - try { - jsonWriter.name(null); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> jsonWriter.name(null)); } @Test @@ -609,17 +584,16 @@ public void testMalformedNumbers() throws IOException { for (String malformedNumber : malformedNumbers) { JsonWriter jsonWriter = new JsonWriter(new StringWriter()); - try { - jsonWriter.value(new LazilyParsedNumber(malformedNumber)); - fail("Should have failed writing malformed number: " + malformedNumber); - } catch (IllegalArgumentException e) { - assertThat(e) - .hasMessageThat() - .isEqualTo( - "String created by class com.google.gson.internal.LazilyParsedNumber is not a valid" - + " JSON number: " - + malformedNumber); - } + var e = + assertThrows( + IllegalArgumentException.class, + () -> jsonWriter.value(new LazilyParsedNumber(malformedNumber))); + assertThat(e) + .hasMessageThat() + .isEqualTo( + "String created by class com.google.gson.internal.LazilyParsedNumber is not a valid" + + " JSON number: " + + malformedNumber); } } @@ -899,26 +873,10 @@ public void testClosedWriterThrowsOnStructure() throws IOException { writer.beginArray(); writer.endArray(); writer.close(); - try { - writer.beginArray(); - fail(); - } catch (IllegalStateException expected) { - } - try { - writer.endArray(); - fail(); - } catch (IllegalStateException expected) { - } - try { - writer.beginObject(); - fail(); - } catch (IllegalStateException expected) { - } - try { - writer.endObject(); - fail(); - } catch (IllegalStateException expected) { - } + assertThrows(IllegalStateException.class, () -> writer.beginArray()); + assertThrows(IllegalStateException.class, () -> writer.endArray()); + assertThrows(IllegalStateException.class, () -> writer.beginObject()); + assertThrows(IllegalStateException.class, () -> writer.endObject()); } @Test @@ -928,11 +886,8 @@ public void testClosedWriterThrowsOnName() throws IOException { writer.beginArray(); writer.endArray(); writer.close(); - try { - writer.name("a"); - fail(); - } catch (IllegalStateException expected) { - } + var e = assertThrows(IllegalStateException.class, () -> writer.name("a")); + assertThat(e).hasMessageThat().isEqualTo("JsonWriter is closed."); } @Test @@ -942,11 +897,8 @@ public void testClosedWriterThrowsOnValue() throws IOException { writer.beginArray(); writer.endArray(); writer.close(); - try { - writer.value("a"); - fail(); - } catch (IllegalStateException expected) { - } + var e = assertThrows(IllegalStateException.class, () -> writer.value("a")); + assertThat(e).hasMessageThat().isEqualTo("JsonWriter is closed."); } @Test @@ -956,11 +908,8 @@ public void testClosedWriterThrowsOnFlush() throws IOException { writer.beginArray(); writer.endArray(); writer.close(); - try { - writer.flush(); - fail(); - } catch (IllegalStateException expected) { - } + var e = assertThrows(IllegalStateException.class, () -> writer.flush()); + assertThat(e).hasMessageThat().isEqualTo("JsonWriter is closed."); } @Test From 20566edb3b38f121688dee0b8920d65e44584aff Mon Sep 17 00:00:00 2001 From: Marcono1234 Date: Sun, 26 May 2024 19:30:29 +0200 Subject: [PATCH 2/7] Use Truth for unit tests in `proto` and `extras` module --- extras/pom.xml | 5 + .../RuntimeTypeAdapterFactory.java | 4 +- .../gson/graph/GraphAdapterBuilderTest.java | 54 +++++---- .../gson/interceptors/InterceptorTest.java | 35 +++--- .../PostConstructAdapterFactoryTest.java | 28 ++--- .../RuntimeTypeAdapterFactoryTest.java | 108 +++++++----------- .../typeadapters/UtcDateTypeAdapterTest.java | 32 +++--- proto/pom.xml | 1 - ...rotosWithComplexAndRepeatedFieldsTest.java | 24 ++-- .../ProtosWithPrimitiveTypesTest.java | 21 ++-- 10 files changed, 139 insertions(+), 173 deletions(-) diff --git a/extras/pom.xml b/extras/pom.xml index 50a65f7136..f9f470a732 100644 --- a/extras/pom.xml +++ b/extras/pom.xml @@ -62,6 +62,11 @@ junit test + + com.google.truth + truth + test + diff --git a/extras/src/main/java/com/google/gson/typeadapters/RuntimeTypeAdapterFactory.java b/extras/src/main/java/com/google/gson/typeadapters/RuntimeTypeAdapterFactory.java index fa70755abd..b260389d01 100644 --- a/extras/src/main/java/com/google/gson/typeadapters/RuntimeTypeAdapterFactory.java +++ b/extras/src/main/java/com/google/gson/typeadapters/RuntimeTypeAdapterFactory.java @@ -184,8 +184,8 @@ public static RuntimeTypeAdapterFactory of( } /** - * 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. */ public static RuntimeTypeAdapterFactory of(Class baseType, String typeFieldName) { return new RuntimeTypeAdapterFactory<>(baseType, typeFieldName, false); diff --git a/extras/src/test/java/com/google/gson/graph/GraphAdapterBuilderTest.java b/extras/src/test/java/com/google/gson/graph/GraphAdapterBuilderTest.java index 5f4b986f53..9c79130d0d 100644 --- a/extras/src/test/java/com/google/gson/graph/GraphAdapterBuilderTest.java +++ b/extras/src/test/java/com/google/gson/graph/GraphAdapterBuilderTest.java @@ -16,15 +16,13 @@ package com.google.gson.graph; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; +import static com.google.common.truth.Truth.assertThat; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; import java.lang.reflect.Type; import java.util.ArrayList; -import java.util.Collections; import java.util.List; import org.junit.Test; @@ -42,11 +40,11 @@ public void testSerialization() { new GraphAdapterBuilder().addType(Roshambo.class).registerOn(gsonBuilder); Gson gson = gsonBuilder.create(); - assertEquals( - "{'0x1':{'name':'ROCK','beats':'0x2'}," - + "'0x2':{'name':'SCISSORS','beats':'0x3'}," - + "'0x3':{'name':'PAPER','beats':'0x1'}}", - gson.toJson(rock).replace('"', '\'')); + assertThat(gson.toJson(rock).replace('"', '\'')) + .isEqualTo( + "{'0x1':{'name':'ROCK','beats':'0x2'}," + + "'0x2':{'name':'SCISSORS','beats':'0x3'}," + + "'0x3':{'name':'PAPER','beats':'0x1'}}"); } @Test @@ -61,12 +59,12 @@ public void testDeserialization() { Gson gson = gsonBuilder.create(); Roshambo rock = gson.fromJson(json, Roshambo.class); - assertEquals("ROCK", rock.name); + assertThat(rock.name).isEqualTo("ROCK"); Roshambo scissors = rock.beats; - assertEquals("SCISSORS", scissors.name); + assertThat(scissors.name).isEqualTo("SCISSORS"); Roshambo paper = scissors.beats; - assertEquals("PAPER", paper.name); - assertSame(rock, paper.beats); + assertThat(paper.name).isEqualTo("PAPER"); + assertThat(paper.beats).isSameInstanceAs(rock); } @Test @@ -78,8 +76,8 @@ public void testDeserializationDirectSelfReference() { Gson gson = gsonBuilder.create(); Roshambo suicide = gson.fromJson(json, Roshambo.class); - assertEquals("SUICIDE", suicide.name); - assertSame(suicide, suicide.beats); + assertThat(suicide.name).isEqualTo("SUICIDE"); + assertThat(suicide.beats).isSameInstanceAs(suicide); } @Test @@ -99,7 +97,7 @@ public void testSerializeListOfLists() { Gson gson = gsonBuilder.create(); String json = gson.toJson(listOfLists, listOfListsType); - assertEquals("{'0x1':['0x1','0x2'],'0x2':[]}", json.replace('"', '\'')); + assertThat(json.replace('"', '\'')).isEqualTo("{'0x1':['0x1','0x2'],'0x2':[]}"); } @Test @@ -115,9 +113,9 @@ public void testDeserializeListOfLists() { Gson gson = gsonBuilder.create(); List> listOfLists = gson.fromJson("{'0x1':['0x1','0x2'],'0x2':[]}", listOfListsType); - assertEquals(2, listOfLists.size()); - assertSame(listOfLists, listOfLists.get(0)); - assertEquals(Collections.emptyList(), listOfLists.get(1)); + assertThat(listOfLists).hasSize(2); + assertThat(listOfLists.get(0)).isSameInstanceAs(listOfLists); + assertThat(listOfLists.get(1)).isEmpty(); } @Test @@ -134,11 +132,11 @@ public void testSerializationWithMultipleTypes() { .registerOn(gsonBuilder); Gson gson = gsonBuilder.create(); - assertEquals( - "{'0x1':{'name':'Google','employees':['0x2','0x3']}," - + "'0x2':{'name':'Jesse','company':'0x1'}," - + "'0x3':{'name':'Joel','company':'0x1'}}", - gson.toJson(google).replace('"', '\'')); + assertThat(gson.toJson(google).replace('"', '\'')) + .isEqualTo( + "{'0x1':{'name':'Google','employees':['0x2','0x3']}," + + "'0x2':{'name':'Jesse','company':'0x1'}," + + "'0x3':{'name':'Joel','company':'0x1'}}"); } @Test @@ -155,13 +153,13 @@ public void testDeserializationWithMultipleTypes() { + "'0x2':{'name':'Jesse','company':'0x1'}," + "'0x3':{'name':'Joel','company':'0x1'}}"; Company company = gson.fromJson(json, Company.class); - assertEquals("Google", company.name); + assertThat(company.name).isEqualTo("Google"); Employee jesse = company.employees.get(0); - assertEquals("Jesse", jesse.name); - assertEquals(company, jesse.company); + assertThat(jesse.name).isEqualTo("Jesse"); + assertThat(jesse.company).isEqualTo(company); Employee joel = company.employees.get(1); - assertEquals("Joel", joel.name); - assertEquals(company, joel.company); + assertThat(joel.name).isEqualTo("Joel"); + assertThat(joel.company).isEqualTo(company); } static class Roshambo { diff --git a/extras/src/test/java/com/google/gson/interceptors/InterceptorTest.java b/extras/src/test/java/com/google/gson/interceptors/InterceptorTest.java index 9a957fc744..329fee44d5 100644 --- a/extras/src/test/java/com/google/gson/interceptors/InterceptorTest.java +++ b/extras/src/test/java/com/google/gson/interceptors/InterceptorTest.java @@ -15,8 +15,8 @@ */ package com.google.gson.interceptors; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static com.google.common.truth.Truth.assertThat; +import static org.junit.Assert.assertThrows; import com.google.gson.Gson; import com.google.gson.GsonBuilder; @@ -55,17 +55,13 @@ public void setUp() throws Exception { @Test public void testExceptionsPropagated() { - try { - gson.fromJson("{}", User.class); - fail(); - } catch (JsonParseException expected) { - } + assertThrows(JsonParseException.class, () -> gson.fromJson("{}", User.class)); } @Test public void testTopLevelClass() { User user = gson.fromJson("{name:'bob',password:'pwd'}", User.class); - assertEquals(User.DEFAULT_EMAIL, user.email); + assertThat(user.email).isEqualTo(User.DEFAULT_EMAIL); } @Test @@ -73,7 +69,7 @@ public void testList() { List list = gson.fromJson("[{name:'bob',password:'pwd'}]", new TypeToken>() {}.getType()); User user = list.get(0); - assertEquals(User.DEFAULT_EMAIL, user.email); + assertThat(user.email).isEqualTo(User.DEFAULT_EMAIL); } @Test @@ -82,30 +78,29 @@ public void testCollection() { gson.fromJson( "[{name:'bob',password:'pwd'}]", new TypeToken>() {}.getType()); User user = list.iterator().next(); - assertEquals(User.DEFAULT_EMAIL, user.email); + assertThat(user.email).isEqualTo(User.DEFAULT_EMAIL); } @Test public void testMapKeyAndValues() { Type mapType = new TypeToken>() {}.getType(); - try { - gson.fromJson("[[{name:'bob',password:'pwd'},{}]]", mapType); - fail(); - } catch (JsonSyntaxException expected) { - } + assertThrows( + JsonSyntaxException.class, + () -> gson.fromJson("[[{name:'bob',password:'pwd'},{}]]", mapType)); + Map map = gson.fromJson( "[[{name:'bob',password:'pwd'},{city:'Mountain View',state:'CA',zip:'94043'}]]", mapType); Entry entry = map.entrySet().iterator().next(); - assertEquals(User.DEFAULT_EMAIL, entry.getKey().email); - assertEquals(Address.DEFAULT_FIRST_LINE, entry.getValue().firstLine); + assertThat(entry.getKey().email).isEqualTo(User.DEFAULT_EMAIL); + assertThat(entry.getValue().firstLine).isEqualTo(Address.DEFAULT_FIRST_LINE); } @Test public void testField() { UserGroup userGroup = gson.fromJson("{user:{name:'bob',password:'pwd'}}", UserGroup.class); - assertEquals(User.DEFAULT_EMAIL, userGroup.user.email); + assertThat(userGroup.user.email).isEqualTo(User.DEFAULT_EMAIL); } @Test @@ -134,14 +129,14 @@ public User read(JsonReader in) throws IOException { .registerTypeAdapterFactory(new InterceptorFactory()) .create(); UserGroup userGroup = gson.fromJson("{user:{name:'bob',password:'pwd'}}", UserGroup.class); - assertEquals(User.DEFAULT_EMAIL, userGroup.user.email); + assertThat(userGroup.user.email).isEqualTo(User.DEFAULT_EMAIL); } @Test public void testDirectInvocationOfTypeAdapter() throws Exception { TypeAdapter adapter = gson.getAdapter(UserGroup.class); UserGroup userGroup = adapter.fromJson("{\"user\":{\"name\":\"bob\",\"password\":\"pwd\"}}"); - assertEquals(User.DEFAULT_EMAIL, userGroup.user.email); + assertThat(userGroup.user.email).isEqualTo(User.DEFAULT_EMAIL); } @SuppressWarnings("unused") diff --git a/extras/src/test/java/com/google/gson/typeadapters/PostConstructAdapterFactoryTest.java b/extras/src/test/java/com/google/gson/typeadapters/PostConstructAdapterFactoryTest.java index 1ce937f751..362e982b09 100644 --- a/extras/src/test/java/com/google/gson/typeadapters/PostConstructAdapterFactoryTest.java +++ b/extras/src/test/java/com/google/gson/typeadapters/PostConstructAdapterFactoryTest.java @@ -16,8 +16,8 @@ package com.google.gson.typeadapters; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static com.google.common.truth.Truth.assertThat; +import static org.junit.Assert.assertThrows; import com.google.gson.Gson; import com.google.gson.GsonBuilder; @@ -32,12 +32,14 @@ public void test() throws Exception { Gson gson = new GsonBuilder().registerTypeAdapterFactory(new PostConstructAdapterFactory()).create(); gson.fromJson("{\"bread\": \"white\", \"cheese\": \"cheddar\"}", Sandwich.class); - try { - gson.fromJson("{\"bread\": \"cheesey bread\", \"cheese\": \"swiss\"}", Sandwich.class); - fail(); - } catch (IllegalArgumentException expected) { - assertEquals("too cheesey", expected.getMessage()); - } + + var e = + assertThrows( + IllegalArgumentException.class, + () -> + gson.fromJson( + "{\"bread\": \"cheesey bread\", \"cheese\": \"swiss\"}", Sandwich.class)); + assertThat(e).hasMessageThat().isEqualTo("too cheesey"); } @Test @@ -51,13 +53,13 @@ public void testList() { // Throws NullPointerException without the fix in https://github.com/google/gson/pull/1103 String json = gson.toJson(sandwiches); - assertEquals( - "{\"sandwiches\":[{\"bread\":\"white\",\"cheese\":\"cheddar\"}," - + "{\"bread\":\"whole wheat\",\"cheese\":\"swiss\"}]}", - json); + assertThat(json) + .isEqualTo( + "{\"sandwiches\":[{\"bread\":\"white\",\"cheese\":\"cheddar\"}," + + "{\"bread\":\"whole wheat\",\"cheese\":\"swiss\"}]}"); MultipleSandwiches sandwichesFromJson = gson.fromJson(json, MultipleSandwiches.class); - assertEquals(sandwiches, sandwichesFromJson); + assertThat(sandwichesFromJson).isEqualTo(sandwiches); } @SuppressWarnings({"overrides", "EqualsHashCode"}) // for missing hashCode() override diff --git a/extras/src/test/java/com/google/gson/typeadapters/RuntimeTypeAdapterFactoryTest.java b/extras/src/test/java/com/google/gson/typeadapters/RuntimeTypeAdapterFactoryTest.java index b4018caedc..5a7ed29ffb 100644 --- a/extras/src/test/java/com/google/gson/typeadapters/RuntimeTypeAdapterFactoryTest.java +++ b/extras/src/test/java/com/google/gson/typeadapters/RuntimeTypeAdapterFactoryTest.java @@ -16,10 +16,8 @@ package com.google.gson.typeadapters; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static com.google.common.truth.Truth.assertThat; +import static org.junit.Assert.assertThrows; import com.google.gson.Gson; import com.google.gson.GsonBuilder; @@ -36,13 +34,12 @@ public void testRuntimeTypeAdapter() { Gson gson = new GsonBuilder().registerTypeAdapterFactory(rta).create(); CreditCard original = new CreditCard("Jesse", 234); - assertEquals( - "{\"type\":\"CreditCard\",\"cvv\":234,\"ownerName\":\"Jesse\"}", - gson.toJson(original, BillingInstrument.class)); + assertThat(gson.toJson(original, BillingInstrument.class)) + .isEqualTo("{\"type\":\"CreditCard\",\"cvv\":234,\"ownerName\":\"Jesse\"}"); BillingInstrument deserialized = gson.fromJson("{type:'CreditCard',cvv:234,ownerName:'Jesse'}", BillingInstrument.class); - assertEquals("Jesse", deserialized.ownerName); - assertTrue(deserialized instanceof CreditCard); + assertThat(deserialized.ownerName).isEqualTo("Jesse"); + assertThat(deserialized).isInstanceOf(CreditCard.class); } @Test @@ -57,12 +54,12 @@ public void testRuntimeTypeAdapterRecognizeSubtypes() { Gson gson = new GsonBuilder().registerTypeAdapterFactory(rta).create(); CreditCard original = new CreditCard("Jesse", 234); - assertEquals( - "{\"type\":\"CreditCard\",\"cvv\":234,\"ownerName\":\"Jesse\"}", gson.toJson(original)); + assertThat(gson.toJson(original)) + .isEqualTo("{\"type\":\"CreditCard\",\"cvv\":234,\"ownerName\":\"Jesse\"}"); BillingInstrument deserialized = gson.fromJson("{type:'CreditCard',cvv:234,ownerName:'Jesse'}", BillingInstrument.class); - assertEquals("Jesse", deserialized.ownerName); - assertTrue(deserialized instanceof CreditCard); + assertThat(deserialized.ownerName).isEqualTo("Jesse"); + assertThat(deserialized).isInstanceOf(CreditCard.class); } @Test @@ -73,52 +70,37 @@ public void testRuntimeTypeIsBaseType() { Gson gson = new GsonBuilder().registerTypeAdapterFactory(rta).create(); BillingInstrument original = new BillingInstrument("Jesse"); - assertEquals( - "{\"type\":\"BillingInstrument\",\"ownerName\":\"Jesse\"}", - gson.toJson(original, BillingInstrument.class)); + assertThat(gson.toJson(original, BillingInstrument.class)) + .isEqualTo("{\"type\":\"BillingInstrument\",\"ownerName\":\"Jesse\"}"); BillingInstrument deserialized = gson.fromJson("{type:'BillingInstrument',ownerName:'Jesse'}", BillingInstrument.class); - assertEquals("Jesse", deserialized.ownerName); + assertThat(deserialized.ownerName).isEqualTo("Jesse"); } @Test public void testNullBaseType() { - try { - RuntimeTypeAdapterFactory.of(null); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> RuntimeTypeAdapterFactory.of(null)); } @Test public void testNullTypeFieldName() { - try { - RuntimeTypeAdapterFactory.of(BillingInstrument.class, null); - fail(); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, + () -> RuntimeTypeAdapterFactory.of(BillingInstrument.class, null)); } @Test public void testNullSubtype() { RuntimeTypeAdapterFactory rta = RuntimeTypeAdapterFactory.of(BillingInstrument.class); - try { - rta.registerSubtype(null); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> rta.registerSubtype(null)); } @Test public void testNullLabel() { RuntimeTypeAdapterFactory rta = RuntimeTypeAdapterFactory.of(BillingInstrument.class); - try { - rta.registerSubtype(CreditCard.class, null); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> rta.registerSubtype(CreditCard.class, null)); } @Test @@ -126,11 +108,10 @@ public void testDuplicateSubtype() { RuntimeTypeAdapterFactory rta = RuntimeTypeAdapterFactory.of(BillingInstrument.class); rta.registerSubtype(CreditCard.class, "CC"); - try { - rta.registerSubtype(CreditCard.class, "Visa"); - fail(); - } catch (IllegalArgumentException expected) { - } + var e = + assertThrows( + IllegalArgumentException.class, () -> rta.registerSubtype(CreditCard.class, "Visa")); + assertThat(e).hasMessageThat().isEqualTo("types and labels must be unique"); } @Test @@ -138,11 +119,10 @@ public void testDuplicateLabel() { RuntimeTypeAdapterFactory rta = RuntimeTypeAdapterFactory.of(BillingInstrument.class); rta.registerSubtype(CreditCard.class, "CC"); - try { - rta.registerSubtype(BankTransfer.class, "CC"); - fail(); - } catch (IllegalArgumentException expected) { - } + var e = + assertThrows( + IllegalArgumentException.class, () -> rta.registerSubtype(BankTransfer.class, "CC")); + assertThat(e).hasMessageThat().isEqualTo("types and labels must be unique"); } @Test @@ -150,11 +130,9 @@ public void testDeserializeMissingTypeField() { TypeAdapterFactory billingAdapter = RuntimeTypeAdapterFactory.of(BillingInstrument.class).registerSubtype(CreditCard.class); Gson gson = new GsonBuilder().registerTypeAdapterFactory(billingAdapter).create(); - try { - gson.fromJson("{ownerName:'Jesse'}", BillingInstrument.class); - fail(); - } catch (JsonParseException expected) { - } + assertThrows( + JsonParseException.class, + () -> gson.fromJson("{ownerName:'Jesse'}", BillingInstrument.class)); } @Test @@ -162,11 +140,9 @@ public void testDeserializeMissingSubtype() { TypeAdapterFactory billingAdapter = RuntimeTypeAdapterFactory.of(BillingInstrument.class).registerSubtype(BankTransfer.class); Gson gson = new GsonBuilder().registerTypeAdapterFactory(billingAdapter).create(); - try { - gson.fromJson("{type:'CreditCard',ownerName:'Jesse'}", BillingInstrument.class); - fail(); - } catch (JsonParseException expected) { - } + assertThrows( + JsonParseException.class, + () -> gson.fromJson("{type:'CreditCard',ownerName:'Jesse'}", BillingInstrument.class)); } @Test @@ -174,11 +150,9 @@ public void testSerializeMissingSubtype() { TypeAdapterFactory billingAdapter = RuntimeTypeAdapterFactory.of(BillingInstrument.class).registerSubtype(BankTransfer.class); Gson gson = new GsonBuilder().registerTypeAdapterFactory(billingAdapter).create(); - try { - gson.toJson(new CreditCard("Jesse", 456), BillingInstrument.class); - fail(); - } catch (JsonParseException expected) { - } + assertThrows( + JsonParseException.class, + () -> gson.toJson(new CreditCard("Jesse", 456), BillingInstrument.class)); } @Test @@ -187,11 +161,9 @@ public void testSerializeCollidingTypeFieldName() { RuntimeTypeAdapterFactory.of(BillingInstrument.class, "cvv") .registerSubtype(CreditCard.class); Gson gson = new GsonBuilder().registerTypeAdapterFactory(billingAdapter).create(); - try { - gson.toJson(new CreditCard("Jesse", 456), BillingInstrument.class); - fail(); - } catch (JsonParseException expected) { - } + assertThrows( + JsonParseException.class, + () -> gson.toJson(new CreditCard("Jesse", 456), BillingInstrument.class)); } @Test @@ -205,7 +177,7 @@ public void testSerializeWrappedNullValue() { gson.toJson(new BillingInstrumentWrapper(null), BillingInstrumentWrapper.class); BillingInstrumentWrapper deserialized = gson.fromJson(serialized, BillingInstrumentWrapper.class); - assertNull(deserialized.instrument); + assertThat(deserialized.instrument).isNull(); } static class BillingInstrumentWrapper { diff --git a/extras/src/test/java/com/google/gson/typeadapters/UtcDateTypeAdapterTest.java b/extras/src/test/java/com/google/gson/typeadapters/UtcDateTypeAdapterTest.java index 771e7648e9..7141ec80ba 100644 --- a/extras/src/test/java/com/google/gson/typeadapters/UtcDateTypeAdapterTest.java +++ b/extras/src/test/java/com/google/gson/typeadapters/UtcDateTypeAdapterTest.java @@ -16,8 +16,8 @@ package com.google.gson.typeadapters; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static com.google.common.truth.Truth.assertThat; +import static org.junit.Assert.assertThrows; import com.google.gson.Gson; import com.google.gson.GsonBuilder; @@ -39,7 +39,7 @@ public void testLocalTimeZone() { Date expected = new Date(); String json = gson.toJson(expected); Date actual = gson.fromJson(json, Date.class); - assertEquals(expected.getTime(), actual.getTime()); + assertThat(actual.getTime()).isEqualTo(expected.getTime()); } @Test @@ -50,7 +50,7 @@ public void testDifferentTimeZones() { String json = gson.toJson(expected); // System.out.println(json + ": " + timeZone); Date actual = gson.fromJson(json, Date.class); - assertEquals(expected.getTime(), actual.getTime()); + assertThat(actual.getTime()).isEqualTo(expected.getTime()); } } @@ -62,7 +62,8 @@ public void testDifferentTimeZones() { public void testUtcDatesOnJdkBefore1_7() { Gson gson = new GsonBuilder().registerTypeAdapter(Date.class, new UtcDateTypeAdapter()).create(); - Date unused = gson.fromJson("'2014-12-05T04:00:00.000Z'", Date.class); + Date date = gson.fromJson("'2014-12-05T04:00:00.000Z'", Date.class); + assertThat(date.getTime()).isEqualTo(1417752000000L); } @Test @@ -73,26 +74,25 @@ public void testUtcWithJdk7Default() { iso8601Format.setTimeZone(TimeZone.getTimeZone("UTC")); String expectedJson = "\"" + iso8601Format.format(expected) + "\""; String actualJson = gson.toJson(expected); - assertEquals(expectedJson, actualJson); + assertThat(actualJson).isEqualTo(expectedJson); Date actual = gson.fromJson(expectedJson, Date.class); - assertEquals(expected.getTime(), actual.getTime()); + assertThat(actual.getTime()).isEqualTo(expected.getTime()); } @Test public void testNullDateSerialization() { String json = gson.toJson(null, Date.class); - assertEquals("null", json); + assertThat(json).isEqualTo("null"); } @Test public void testWellFormedParseException() { - try { - gson.fromJson("2017-06-20T14:32:30", Date.class); - fail("No exception"); - } catch (JsonParseException exe) { - assertEquals( - "java.text.ParseException: Failed to parse date ['2017-06-20T14']: 2017-06-20T14", - exe.getMessage()); - } + var e = + 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"); } } diff --git a/proto/pom.xml b/proto/pom.xml index 6eecfc4dcf..ca0e496523 100644 --- a/proto/pom.xml +++ b/proto/pom.xml @@ -66,7 +66,6 @@ junit test - com.google.truth truth diff --git a/proto/src/test/java/com/google/gson/protobuf/functional/ProtosWithComplexAndRepeatedFieldsTest.java b/proto/src/test/java/com/google/gson/protobuf/functional/ProtosWithComplexAndRepeatedFieldsTest.java index 367aefc43b..e0be7441e3 100644 --- a/proto/src/test/java/com/google/gson/protobuf/functional/ProtosWithComplexAndRepeatedFieldsTest.java +++ b/proto/src/test/java/com/google/gson/protobuf/functional/ProtosWithComplexAndRepeatedFieldsTest.java @@ -15,8 +15,7 @@ */ package com.google.gson.protobuf.functional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static com.google.common.truth.Truth.assertThat; import com.google.common.base.CaseFormat; import com.google.gson.Gson; @@ -71,19 +70,17 @@ public void testSerializeRepeatedFields() { .addSimples(SimpleProto.newBuilder().setCount(3).build()) .build(); String json = gson.toJson(proto); - assertTrue(json.contains("[2,3]")); - assertTrue(json.contains("foo")); - assertTrue(json.contains("count")); + assertThat(json).isEqualTo("{\"numbers\":[2,3],\"simples\":[{\"msg\":\"foo\"},{\"count\":3}]}"); } @Test public void testDeserializeRepeatedFieldsProto() { String json = "{numbers:[4,6],simples:[{msg:'bar'},{count:7}]}"; ProtoWithRepeatedFields proto = gson.fromJson(json, ProtoWithRepeatedFields.class); - assertEquals(4, proto.getNumbers(0)); - assertEquals(6, proto.getNumbers(1)); - assertEquals("bar", proto.getSimples(0).getMsg()); - assertEquals(7, proto.getSimples(1).getCount()); + assertThat(proto.getNumbers(0)).isEqualTo(4); + assertThat(proto.getNumbers(1)).isEqualTo(6); + assertThat(proto.getSimples(0).getMsg()).isEqualTo("bar"); + assertThat(proto.getSimples(1).getCount()).isEqualTo(7); } @Test @@ -94,8 +91,9 @@ public void testSerializeDifferentCaseFormat() { .addNameThatTestsCaseFormat("bar") .build(); final JsonObject json = upperCamelGson.toJsonTree(proto).getAsJsonObject(); - assertEquals("foo", json.get("AnotherField").getAsString()); - assertEquals("bar", json.get("NameThatTestsCaseFormat").getAsJsonArray().get(0).getAsString()); + assertThat(json.get("AnotherField").getAsString()).isEqualTo("foo"); + assertThat(json.get("NameThatTestsCaseFormat").getAsJsonArray().get(0).getAsString()) + .isEqualTo("bar"); } @Test @@ -103,7 +101,7 @@ public void testDeserializeDifferentCaseFormat() { final String json = "{NameThatTestsCaseFormat:['bar'],AnotherField:'foo'}"; ProtoWithDifferentCaseFormat proto = upperCamelGson.fromJson(json, ProtoWithDifferentCaseFormat.class); - assertEquals("foo", proto.getAnotherField()); - assertEquals("bar", proto.getNameThatTestsCaseFormat(0)); + assertThat(proto.getAnotherField()).isEqualTo("foo"); + assertThat(proto.getNameThatTestsCaseFormat(0)).isEqualTo("bar"); } } diff --git a/proto/src/test/java/com/google/gson/protobuf/functional/ProtosWithPrimitiveTypesTest.java b/proto/src/test/java/com/google/gson/protobuf/functional/ProtosWithPrimitiveTypesTest.java index 4bfd7241c4..2ca0867017 100644 --- a/proto/src/test/java/com/google/gson/protobuf/functional/ProtosWithPrimitiveTypesTest.java +++ b/proto/src/test/java/com/google/gson/protobuf/functional/ProtosWithPrimitiveTypesTest.java @@ -15,9 +15,7 @@ */ package com.google.gson.protobuf.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; @@ -47,35 +45,34 @@ public void setUp() throws Exception { public void testSerializeEmptyProto() { SimpleProto proto = SimpleProto.newBuilder().build(); String json = gson.toJson(proto); - assertEquals("{}", json); + assertThat(json).isEqualTo("{}"); } @Test public void testDeserializeEmptyProto() { SimpleProto proto = gson.fromJson("{}", SimpleProto.class); - assertFalse(proto.hasCount()); - assertFalse(proto.hasMsg()); + assertThat(proto.hasCount()).isFalse(); + assertThat(proto.hasMsg()).isFalse(); } @Test public void testSerializeProto() { SimpleProto proto = SimpleProto.newBuilder().setCount(3).setMsg("foo").build(); String json = gson.toJson(proto); - assertTrue(json.contains("\"msg\":\"foo\"")); - assertTrue(json.contains("\"count\":3")); + assertThat(json).isEqualTo("{\"msg\":\"foo\",\"count\":3}"); } @Test public void testDeserializeProto() { SimpleProto proto = gson.fromJson("{msg:'foo',count:3}", SimpleProto.class); - assertEquals("foo", proto.getMsg()); - assertEquals(3, proto.getCount()); + assertThat(proto.getMsg()).isEqualTo("foo"); + assertThat(proto.getCount()).isEqualTo(3); } @Test public void testDeserializeWithExplicitNullValue() { SimpleProto proto = gson.fromJson("{msg:'foo',count:null}", SimpleProto.class); - assertEquals("foo", proto.getMsg()); - assertEquals(0, proto.getCount()); + assertThat(proto.getMsg()).isEqualTo("foo"); + assertThat(proto.getCount()).isEqualTo(0); } } From 7bbea12f45913f6813b3bb7da714ec2563d40f53 Mon Sep 17 00:00:00 2001 From: Marcono1234 Date: Sun, 26 May 2024 19:46:19 +0200 Subject: [PATCH 3/7] Perform assertions on some currently unused test variables --- .../gson/interceptors/InterceptorTest.java | 4 +-- .../java/com/google/gson/MixedStreamTest.java | 6 ++-- .../gson/functional/ConcurrencyTest.java | 29 ++++++++++++------- .../google/gson/functional/ObjectTest.java | 16 +++++++--- .../google/gson/internal/GsonTypesTest.java | 4 +-- 5 files changed, 38 insertions(+), 21 deletions(-) diff --git a/extras/src/test/java/com/google/gson/interceptors/InterceptorTest.java b/extras/src/test/java/com/google/gson/interceptors/InterceptorTest.java index 329fee44d5..bba0d06b64 100644 --- a/extras/src/test/java/com/google/gson/interceptors/InterceptorTest.java +++ b/extras/src/test/java/com/google/gson/interceptors/InterceptorTest.java @@ -118,9 +118,9 @@ public void write(JsonWriter out, User value) throws IOException { @Override public User read(JsonReader in) throws IOException { in.beginObject(); - String unused1 = in.nextName(); + assertThat(in.nextName()).isEqualTo("name"); String name = in.nextString(); - String unused2 = in.nextName(); + assertThat(in.nextName()).isEqualTo("password"); String password = in.nextString(); in.endObject(); return new User(name, password); diff --git a/gson/src/test/java/com/google/gson/MixedStreamTest.java b/gson/src/test/java/com/google/gson/MixedStreamTest.java index 2dd53bbf46..e3d2fa03c8 100644 --- a/gson/src/test/java/com/google/gson/MixedStreamTest.java +++ b/gson/src/test/java/com/google/gson/MixedStreamTest.java @@ -88,11 +88,13 @@ public void testReaderDoesNotMutateState() throws IOException { jsonReader.beginArray(); jsonReader.setLenient(false); - Car unused1 = gson.fromJson(jsonReader, Car.class); + Car deserialized = gson.fromJson(jsonReader, Car.class); + assertThat(deserialized).isNotNull(); assertThat(jsonReader.isLenient()).isFalse(); jsonReader.setLenient(true); - Car unused2 = gson.fromJson(jsonReader, Car.class); + deserialized = gson.fromJson(jsonReader, Car.class); + assertThat(deserialized).isNotNull(); assertThat(jsonReader.isLenient()).isTrue(); } diff --git a/gson/src/test/java/com/google/gson/functional/ConcurrencyTest.java b/gson/src/test/java/com/google/gson/functional/ConcurrencyTest.java index 3c5d5e5f45..f0e389eef4 100644 --- a/gson/src/test/java/com/google/gson/functional/ConcurrencyTest.java +++ b/gson/src/test/java/com/google/gson/functional/ConcurrencyTest.java @@ -21,7 +21,7 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; -import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; import org.junit.Before; import org.junit.Test; @@ -47,7 +47,7 @@ public void setUp() throws Exception { public void testSingleThreadSerialization() { MyObject myObj = new MyObject(); for (int i = 0; i < 10; i++) { - String unused = gson.toJson(myObj); + assertThat(gson.toJson(myObj)).isEqualTo("{\"a\":\"hello\",\"b\":\"world\",\"i\":42}"); } } @@ -58,7 +58,10 @@ public void testSingleThreadSerialization() { @Test public void testSingleThreadDeserialization() { for (int i = 0; i < 10; i++) { - MyObject unused = gson.fromJson("{'a':'hello','b':'world','i':1}", MyObject.class); + MyObject deserialized = gson.fromJson("{'a':'hello','b':'world','i':1}", MyObject.class); + assertThat(deserialized.a).isEqualTo("hello"); + assertThat(deserialized.b).isEqualTo("world"); + assertThat(deserialized.i).isEqualTo(1); } } @@ -70,7 +73,7 @@ public void testSingleThreadDeserialization() { public void testMultiThreadSerialization() throws InterruptedException { final CountDownLatch startLatch = new CountDownLatch(1); final CountDownLatch finishedLatch = new CountDownLatch(10); - final AtomicBoolean failed = new AtomicBoolean(false); + final AtomicReference error = new AtomicReference<>(null); ExecutorService executor = Executors.newFixedThreadPool(10); for (int taskCount = 0; taskCount < 10; taskCount++) { executor.execute( @@ -81,10 +84,11 @@ public void run() { try { startLatch.await(); for (int i = 0; i < 10; i++) { - String unused = gson.toJson(myObj); + assertThat(gson.toJson(myObj)) + .isEqualTo("{\"a\":\"hello\",\"b\":\"world\",\"i\":42}"); } } catch (Throwable t) { - failed.set(true); + error.set(t); } finally { finishedLatch.countDown(); } @@ -93,7 +97,7 @@ public void run() { } startLatch.countDown(); finishedLatch.await(); - assertThat(failed.get()).isFalse(); + assertThat(error.get()).isNull(); } /** @@ -104,7 +108,7 @@ public void run() { public void testMultiThreadDeserialization() throws InterruptedException { final CountDownLatch startLatch = new CountDownLatch(1); final CountDownLatch finishedLatch = new CountDownLatch(10); - final AtomicBoolean failed = new AtomicBoolean(false); + final AtomicReference error = new AtomicReference<>(null); ExecutorService executor = Executors.newFixedThreadPool(10); for (int taskCount = 0; taskCount < 10; taskCount++) { executor.execute( @@ -114,11 +118,14 @@ public void run() { try { startLatch.await(); for (int i = 0; i < 10; i++) { - MyObject unused = + MyObject deserialized = gson.fromJson("{'a':'hello','b':'world','i':1}", MyObject.class); + assertThat(deserialized.a).isEqualTo("hello"); + assertThat(deserialized.b).isEqualTo("world"); + assertThat(deserialized.i).isEqualTo(1); } } catch (Throwable t) { - failed.set(true); + error.set(t); } finally { finishedLatch.countDown(); } @@ -127,7 +134,7 @@ public void run() { } startLatch.countDown(); finishedLatch.await(); - assertThat(failed.get()).isFalse(); + assertThat(error.get()).isNull(); } @SuppressWarnings("unused") diff --git a/gson/src/test/java/com/google/gson/functional/ObjectTest.java b/gson/src/test/java/com/google/gson/functional/ObjectTest.java index b7e50610e6..935858cb64 100644 --- a/gson/src/test/java/com/google/gson/functional/ObjectTest.java +++ b/gson/src/test/java/com/google/gson/functional/ObjectTest.java @@ -624,18 +624,24 @@ public void testSingletonLists() { Gson gson = new Gson(); Product product = new Product(); assertThat(gson.toJson(product)).isEqualTo("{\"attributes\":[],\"departments\":[]}"); - Product unused1 = gson.fromJson(gson.toJson(product), Product.class); + Product deserialized = gson.fromJson(gson.toJson(product), Product.class); + assertThat(deserialized.attributes).isEmpty(); + assertThat(deserialized.departments).isEmpty(); product.departments.add(new Department()); assertThat(gson.toJson(product)) .isEqualTo("{\"attributes\":[],\"departments\":[{\"name\":\"abc\",\"code\":\"123\"}]}"); - Product unused2 = gson.fromJson(gson.toJson(product), Product.class); + deserialized = gson.fromJson(gson.toJson(product), Product.class); + assertThat(deserialized.attributes).isEmpty(); + assertThat(deserialized.departments).hasSize(1); product.attributes.add("456"); assertThat(gson.toJson(product)) .isEqualTo( "{\"attributes\":[\"456\"],\"departments\":[{\"name\":\"abc\",\"code\":\"123\"}]}"); - Product unused3 = gson.fromJson(gson.toJson(product), Product.class); + deserialized = gson.fromJson(gson.toJson(product), Product.class); + assertThat(deserialized.attributes).containsExactly("456"); + assertThat(deserialized.departments).hasSize(1); } static final class Department { @@ -695,7 +701,9 @@ public void testStaticFieldSerialization() { @Test public void testStaticFieldDeserialization() { // By default Gson should ignore static fields - ClassWithStaticField unused = gson.fromJson("{\"s\":\"custom\"}", ClassWithStaticField.class); + ClassWithStaticField deserialized = + gson.fromJson("{\"s\":\"custom\"}", ClassWithStaticField.class); + assertThat(deserialized).isNotNull(); assertThat(ClassWithStaticField.s).isEqualTo("initial"); Gson gson = diff --git a/gson/src/test/java/com/google/gson/internal/GsonTypesTest.java b/gson/src/test/java/com/google/gson/internal/GsonTypesTest.java index 8534e99195..a877581bb9 100644 --- a/gson/src/test/java/com/google/gson/internal/GsonTypesTest.java +++ b/gson/src/test/java/com/google/gson/internal/GsonTypesTest.java @@ -125,10 +125,10 @@ public void testEqualsOnConstructorParameterTypeVariables() throws Exception { private static final class TypeVariableTest { - @SuppressWarnings({"UnusedMethod", "UnusedVariable", "TypeParameterUnusedInFormals"}) + @SuppressWarnings("unused") public TypeVariableTest(T parameter) {} - @SuppressWarnings({"UnusedMethod", "UnusedVariable", "TypeParameterUnusedInFormals"}) + @SuppressWarnings({"unused", "TypeParameterUnusedInFormals"}) public T method() { return null; } From f01d3940da205d6019a5c518dc46fddb0bcdded6 Mon Sep 17 00:00:00 2001 From: Marcono1234 Date: Sun, 26 May 2024 23:15:14 +0200 Subject: [PATCH 4/7] Improve tests --- .../RuntimeTypeAdapterFactory.java | 4 +-- .../gson/interceptors/InterceptorTest.java | 3 +- .../typeadapters/UtcDateTypeAdapterTest.java | 4 +-- .../com/google/gson/GsonTypeAdapterTest.java | 18 ++++++++---- .../gson/functional/Java17RecordTest.java | 26 ++++++++--------- .../gson/functional/JsonParserTest.java | 10 +++++-- .../functional/MapAsArrayTypeAdapterTest.java | 3 +- .../google/gson/functional/ObjectTest.java | 6 ++-- .../google/gson/functional/PrimitiveTest.java | 2 +- .../gson/functional/ReadersWritersTest.java | 14 +++++++-- .../functional/StreamingTypeAdaptersTest.java | 1 - .../internal/bind/JsonElementReaderTest.java | 3 +- .../google/gson/stream/JsonReaderTest.java | 29 +++++++++++-------- .../functional/ProtosWithAnnotationsTest.java | 9 ++---- 14 files changed, 79 insertions(+), 53 deletions(-) diff --git a/extras/src/main/java/com/google/gson/typeadapters/RuntimeTypeAdapterFactory.java b/extras/src/main/java/com/google/gson/typeadapters/RuntimeTypeAdapterFactory.java index b260389d01..f705cd4628 100644 --- a/extras/src/main/java/com/google/gson/typeadapters/RuntimeTypeAdapterFactory.java +++ b/extras/src/main/java/com/google/gson/typeadapters/RuntimeTypeAdapterFactory.java @@ -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 */ diff --git a/extras/src/test/java/com/google/gson/interceptors/InterceptorTest.java b/extras/src/test/java/com/google/gson/interceptors/InterceptorTest.java index bba0d06b64..e6eae834df 100644 --- a/extras/src/test/java/com/google/gson/interceptors/InterceptorTest.java +++ b/extras/src/test/java/com/google/gson/interceptors/InterceptorTest.java @@ -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 diff --git a/extras/src/test/java/com/google/gson/typeadapters/UtcDateTypeAdapterTest.java b/extras/src/test/java/com/google/gson/typeadapters/UtcDateTypeAdapterTest.java index 7141ec80ba..40240cebe9 100644 --- a/extras/src/test/java/com/google/gson/typeadapters/UtcDateTypeAdapterTest.java +++ b/extras/src/test/java/com/google/gson/typeadapters/UtcDateTypeAdapterTest.java @@ -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"); } } diff --git a/gson/src/test/java/com/google/gson/GsonTypeAdapterTest.java b/gson/src/test/java/com/google/gson/GsonTypeAdapterTest.java index 6991c046db..fcf46238aa 100644 --- a/gson/src/test/java/com/google/gson/GsonTypeAdapterTest.java +++ b/gson/src/test/java/com/google/gson/GsonTypeAdapterTest.java @@ -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(); @@ -85,16 +87,20 @@ public void testTypeAdapterDoesNotAffectNonAdaptedTypes() { private static class ExceptionTypeAdapter implements JsonSerializer, JsonDeserializer { + @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; } } diff --git a/gson/src/test/java/com/google/gson/functional/Java17RecordTest.java b/gson/src/test/java/com/google/gson/functional/Java17RecordTest.java index 87e1a4bb4b..d5619d0869 100644 --- a/gson/src/test/java/com/google/gson/functional/Java17RecordTest.java +++ b/gson/src/test/java/com/google/gson/functional/Java17RecordTest.java @@ -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") @@ -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 @@ -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 @@ -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 */ diff --git a/gson/src/test/java/com/google/gson/functional/JsonParserTest.java b/gson/src/test/java/com/google/gson/functional/JsonParserTest.java index 8340175f15..d6225fc5b4 100644 --- a/gson/src/test/java/com/google/gson/functional/JsonParserTest.java +++ b/gson/src/test/java/com/google/gson/functional/JsonParserTest.java @@ -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; @@ -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 @@ -131,6 +133,10 @@ public void testExtraCommasInArrays() { @Test public void testExtraCommasInMaps() { Type type = new TypeToken>() {}.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 $."); } } diff --git a/gson/src/test/java/com/google/gson/functional/MapAsArrayTypeAdapterTest.java b/gson/src/test/java/com/google/gson/functional/MapAsArrayTypeAdapterTest.java index 61944bc4ed..20155bc6b9 100644 --- a/gson/src/test/java/com/google/gson/functional/MapAsArrayTypeAdapterTest.java +++ b/gson/src/test/java/com/google/gson/functional/MapAsArrayTypeAdapterTest.java @@ -66,7 +66,8 @@ public void testTwoTypesCollapseToOneSerialize() { original.put(1.0D, "a"); original.put(1.0F, "b"); Type type = new TypeToken>() {}.getType(); - assertThrows(JsonSyntaxException.class, () -> gson.toJson(original, type)); + var e = assertThrows(JsonSyntaxException.class, () -> gson.toJson(original, type)); + assertThat(e).hasMessageThat().isEqualTo("TODO"); } @Test diff --git a/gson/src/test/java/com/google/gson/functional/ObjectTest.java b/gson/src/test/java/com/google/gson/functional/ObjectTest.java index 935858cb64..39e2fb2416 100644 --- a/gson/src/test/java/com/google/gson/functional/ObjectTest.java +++ b/gson/src/test/java/com/google/gson/functional/ObjectTest.java @@ -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; @@ -241,7 +242,8 @@ public void testEmptyStringDeserialization() { @Test public void testTruncatedDeserialization() { Type type = new TypeToken>() {}.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 @@ -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() { diff --git a/gson/src/test/java/com/google/gson/functional/PrimitiveTest.java b/gson/src/test/java/com/google/gson/functional/PrimitiveTest.java index 8b8842d344..0769338cf6 100644 --- a/gson/src/test/java/com/google/gson/functional/PrimitiveTest.java +++ b/gson/src/test/java/com/google/gson/functional/PrimitiveTest.java @@ -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)); } diff --git a/gson/src/test/java/com/google/gson/functional/ReadersWritersTest.java b/gson/src/test/java/com/google/gson/functional/ReadersWritersTest.java index eb326ff0f3..324ee0c426 100644 --- a/gson/src/test/java/com/google/gson/functional/ReadersWritersTest.java +++ b/gson/src/test/java/com/google/gson/functional/ReadersWritersTest.java @@ -132,13 +132,23 @@ public void testReadWriteTwoObjects() throws IOException { @Test public void testTypeMismatchThrowsJsonSyntaxExceptionForStrings() { Type type = new TypeToken>() {}.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>() {}.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"); } /** diff --git a/gson/src/test/java/com/google/gson/functional/StreamingTypeAdaptersTest.java b/gson/src/test/java/com/google/gson/functional/StreamingTypeAdaptersTest.java index 78fa8a02be..f7bdf3bb14 100644 --- a/gson/src/test/java/com/google/gson/functional/StreamingTypeAdaptersTest.java +++ b/gson/src/test/java/com/google/gson/functional/StreamingTypeAdaptersTest.java @@ -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']}"; diff --git a/gson/src/test/java/com/google/gson/internal/bind/JsonElementReaderTest.java b/gson/src/test/java/com/google/gson/internal/bind/JsonElementReaderTest.java index a108ea5667..a1c182fcaf 100644 --- a/gson/src/test/java/com/google/gson/internal/bind/JsonElementReaderTest.java +++ b/gson/src/test/java/com/google/gson/internal/bind/JsonElementReaderTest.java @@ -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()); diff --git a/gson/src/test/java/com/google/gson/stream/JsonReaderTest.java b/gson/src/test/java/com/google/gson/stream/JsonReaderTest.java index 982852e3cf..0135e345db 100644 --- a/gson/src/test/java/com/google/gson/stream/JsonReaderTest.java +++ b/gson/src/test/java/com/google/gson/stream/JsonReaderTest.java @@ -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); @@ -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); @@ -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); @@ -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); @@ -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()); } @@ -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); @@ -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 @@ -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(); @@ -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(); @@ -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 $"); @@ -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()); @@ -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()); @@ -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()); diff --git a/proto/src/test/java/com/google/gson/protobuf/functional/ProtosWithAnnotationsTest.java b/proto/src/test/java/com/google/gson/protobuf/functional/ProtosWithAnnotationsTest.java index 9be26bfe16..7399170a49 100644 --- a/proto/src/test/java/com/google/gson/protobuf/functional/ProtosWithAnnotationsTest.java +++ b/proto/src/test/java/com/google/gson/protobuf/functional/ProtosWithAnnotationsTest.java @@ -16,7 +16,7 @@ package com.google.gson.protobuf.functional; import static com.google.common.truth.Truth.assertThat; -import static com.google.common.truth.Truth.assertWithMessage; +import static org.junit.Assert.assertThrows; import com.google.common.base.CaseFormat; import com.google.gson.Gson; @@ -165,12 +165,7 @@ public void testProtoWithAnnotations_deserializeUnknownEnumValue() { @Test public void testProtoWithAnnotations_deserializeUnrecognizedEnumValue() { String json = String.format("{ %n" + " \"content\":\"UNRECOGNIZED\"%n" + "}"); - try { - gson.fromJson(json, InnerMessage.class); - assertWithMessage("Should have thrown").fail(); - } catch (JsonParseException e) { - // expected - } + assertThrows(JsonParseException.class, () -> gson.fromJson(json, InnerMessage.class)); } @Test From 512cea3446dcfc96cf75047cfa55ea8d7e45d287 Mon Sep 17 00:00:00 2001 From: Marcono1234 Date: Fri, 7 Jun 2024 20:59:06 +0200 Subject: [PATCH 5/7] Improve non-finite floating point tests Because there is only `Gson.toJson(Object)` (and no primitive specific overloads) the tests were previously testing the adapter for the boxed object, e.g. Double, twice. --- .../google/gson/functional/PrimitiveTest.java | 61 +++++++++++-------- 1 file changed, 37 insertions(+), 24 deletions(-) diff --git a/gson/src/test/java/com/google/gson/functional/PrimitiveTest.java b/gson/src/test/java/com/google/gson/functional/PrimitiveTest.java index 0769338cf6..bc491db13c 100644 --- a/gson/src/test/java/com/google/gson/functional/PrimitiveTest.java +++ b/gson/src/test/java/com/google/gson/functional/PrimitiveTest.java @@ -528,14 +528,15 @@ private static String extractElementFromArray(String json) { @Test public void testDoubleNaNSerializationNotSupportedByDefault() { - var e = assertThrows(IllegalArgumentException.class, () -> gson.toJson(Double.NaN)); + var e = + assertThrows(IllegalArgumentException.class, () -> gson.toJson(Double.NaN, double.class)); assertThat(e) .hasMessageThat() .isEqualTo( "NaN is not a valid double value as per JSON specification. To override this behavior," + " use GsonBuilder.serializeSpecialFloatingPointValues() method."); - e = assertThrows(IllegalArgumentException.class, () -> gson.toJson((Double) Double.NaN)); + e = assertThrows(IllegalArgumentException.class, () -> gson.toJson(Double.NaN, Double.class)); assertThat(e) .hasMessageThat() .isEqualTo( @@ -546,8 +547,8 @@ public void testDoubleNaNSerializationNotSupportedByDefault() { @Test public void testDoubleNaNSerialization() { Gson gson = new GsonBuilder().serializeSpecialFloatingPointValues().create(); - assertThat(gson.toJson(Double.NaN)).isEqualTo("NaN"); - assertThat(gson.toJson((Double) Double.NaN)).isEqualTo("NaN"); + assertThat(gson.toJson(Double.NaN, double.class)).isEqualTo("NaN"); + assertThat(gson.toJson(Double.NaN, Double.class)).isEqualTo("NaN"); } @Test @@ -558,14 +559,14 @@ public void testDoubleNaNDeserialization() { @Test public void testFloatNaNSerializationNotSupportedByDefault() { - var e = assertThrows(IllegalArgumentException.class, () -> gson.toJson(Float.NaN)); + var e = assertThrows(IllegalArgumentException.class, () -> gson.toJson(Float.NaN, float.class)); assertThat(e) .hasMessageThat() .isEqualTo( "NaN is not a valid double value as per JSON specification. To override this behavior," + " use GsonBuilder.serializeSpecialFloatingPointValues() method."); - e = assertThrows(IllegalArgumentException.class, () -> gson.toJson((Float) Float.NaN)); + e = assertThrows(IllegalArgumentException.class, () -> gson.toJson(Float.NaN, Float.class)); assertThat(e) .hasMessageThat() .isEqualTo( @@ -576,8 +577,8 @@ public void testFloatNaNSerializationNotSupportedByDefault() { @Test public void testFloatNaNSerialization() { Gson gson = new GsonBuilder().serializeSpecialFloatingPointValues().create(); - assertThat(gson.toJson(Float.NaN)).isEqualTo("NaN"); - assertThat(gson.toJson((Float) Float.NaN)).isEqualTo("NaN"); + assertThat(gson.toJson(Float.NaN, float.class)).isEqualTo("NaN"); + assertThat(gson.toJson(Float.NaN, Float.class)).isEqualTo("NaN"); } @Test @@ -595,7 +596,9 @@ public void testBigDecimalNaNDeserializationNotSupported() { @Test public void testDoubleInfinitySerializationNotSupportedByDefault() { var e = - assertThrows(IllegalArgumentException.class, () -> gson.toJson(Double.POSITIVE_INFINITY)); + assertThrows( + IllegalArgumentException.class, + () -> gson.toJson(Double.POSITIVE_INFINITY, double.class)); assertThat(e) .hasMessageThat() .isEqualTo( @@ -604,7 +607,8 @@ public void testDoubleInfinitySerializationNotSupportedByDefault() { e = assertThrows( - IllegalArgumentException.class, () -> gson.toJson((Double) Double.POSITIVE_INFINITY)); + IllegalArgumentException.class, + () -> gson.toJson(Double.POSITIVE_INFINITY, Double.class)); assertThat(e) .hasMessageThat() .isEqualTo( @@ -615,8 +619,8 @@ public void testDoubleInfinitySerializationNotSupportedByDefault() { @Test public void testDoubleInfinitySerialization() { Gson gson = new GsonBuilder().serializeSpecialFloatingPointValues().create(); - assertThat(gson.toJson(Double.POSITIVE_INFINITY)).isEqualTo("Infinity"); - assertThat(gson.toJson((Double) Double.POSITIVE_INFINITY)).isEqualTo("Infinity"); + assertThat(gson.toJson(Double.POSITIVE_INFINITY, double.class)).isEqualTo("Infinity"); + assertThat(gson.toJson(Double.POSITIVE_INFINITY, Double.class)).isEqualTo("Infinity"); } @Test @@ -628,7 +632,9 @@ public void testDoubleInfinityDeserialization() { @Test public void testFloatInfinitySerializationNotSupportedByDefault() { var e = - assertThrows(IllegalArgumentException.class, () -> gson.toJson(Float.POSITIVE_INFINITY)); + assertThrows( + IllegalArgumentException.class, + () -> gson.toJson(Float.POSITIVE_INFINITY, float.class)); assertThat(e) .hasMessageThat() .isEqualTo( @@ -637,7 +643,8 @@ public void testFloatInfinitySerializationNotSupportedByDefault() { e = assertThrows( - IllegalArgumentException.class, () -> gson.toJson((Float) Float.POSITIVE_INFINITY)); + IllegalArgumentException.class, + () -> gson.toJson(Float.POSITIVE_INFINITY, Float.class)); assertThat(e) .hasMessageThat() .isEqualTo( @@ -648,8 +655,8 @@ public void testFloatInfinitySerializationNotSupportedByDefault() { @Test public void testFloatInfinitySerialization() { Gson gson = new GsonBuilder().serializeSpecialFloatingPointValues().create(); - assertThat(gson.toJson(Float.POSITIVE_INFINITY)).isEqualTo("Infinity"); - assertThat(gson.toJson((Float) Float.POSITIVE_INFINITY)).isEqualTo("Infinity"); + assertThat(gson.toJson(Float.POSITIVE_INFINITY, float.class)).isEqualTo("Infinity"); + assertThat(gson.toJson(Float.POSITIVE_INFINITY, Float.class)).isEqualTo("Infinity"); } @Test @@ -667,7 +674,9 @@ public void testBigDecimalInfinityDeserializationNotSupported() { @Test public void testNegativeInfinitySerializationNotSupportedByDefault() { var e = - assertThrows(IllegalArgumentException.class, () -> gson.toJson(Double.NEGATIVE_INFINITY)); + assertThrows( + IllegalArgumentException.class, + () -> gson.toJson(Double.NEGATIVE_INFINITY, double.class)); assertThat(e) .hasMessageThat() .isEqualTo( @@ -676,7 +685,8 @@ public void testNegativeInfinitySerializationNotSupportedByDefault() { e = assertThrows( - IllegalArgumentException.class, () -> gson.toJson((Double) Double.NEGATIVE_INFINITY)); + IllegalArgumentException.class, + () -> gson.toJson(Double.NEGATIVE_INFINITY, Double.class)); assertThat(e) .hasMessageThat() .isEqualTo( @@ -687,8 +697,8 @@ public void testNegativeInfinitySerializationNotSupportedByDefault() { @Test public void testNegativeInfinitySerialization() { Gson gson = new GsonBuilder().serializeSpecialFloatingPointValues().create(); - assertThat(gson.toJson(Double.NEGATIVE_INFINITY)).isEqualTo("-Infinity"); - assertThat(gson.toJson((Double) Double.NEGATIVE_INFINITY)).isEqualTo("-Infinity"); + assertThat(gson.toJson(Double.NEGATIVE_INFINITY, double.class)).isEqualTo("-Infinity"); + assertThat(gson.toJson(Double.NEGATIVE_INFINITY, Double.class)).isEqualTo("-Infinity"); } @Test @@ -700,7 +710,9 @@ public void testNegativeInfinityDeserialization() { @Test public void testNegativeInfinityFloatSerializationNotSupportedByDefault() { var e = - assertThrows(IllegalArgumentException.class, () -> gson.toJson(Float.NEGATIVE_INFINITY)); + assertThrows( + IllegalArgumentException.class, + () -> gson.toJson(Float.NEGATIVE_INFINITY, float.class)); assertThat(e) .hasMessageThat() .isEqualTo( @@ -709,7 +721,8 @@ public void testNegativeInfinityFloatSerializationNotSupportedByDefault() { e = assertThrows( - IllegalArgumentException.class, () -> gson.toJson((Float) Float.NEGATIVE_INFINITY)); + IllegalArgumentException.class, + () -> gson.toJson(Float.NEGATIVE_INFINITY, Float.class)); assertThat(e) .hasMessageThat() .isEqualTo( @@ -720,8 +733,8 @@ public void testNegativeInfinityFloatSerializationNotSupportedByDefault() { @Test public void testNegativeInfinityFloatSerialization() { Gson gson = new GsonBuilder().serializeSpecialFloatingPointValues().create(); - assertThat(gson.toJson(Float.NEGATIVE_INFINITY)).isEqualTo("-Infinity"); - assertThat(gson.toJson((Float) Float.NEGATIVE_INFINITY)).isEqualTo("-Infinity"); + assertThat(gson.toJson(Float.NEGATIVE_INFINITY, float.class)).isEqualTo("-Infinity"); + assertThat(gson.toJson(Float.NEGATIVE_INFINITY, Float.class)).isEqualTo("-Infinity"); } @Test From 9f8620d7dd9c8ae236533128b0a2ef7e60585f61 Mon Sep 17 00:00:00 2001 From: Marcono1234 Date: Fri, 7 Jun 2024 23:58:16 +0200 Subject: [PATCH 6/7] Improve tests --- .../gson/interceptors/InterceptorTest.java | 8 +- .../RuntimeTypeAdapterFactoryTest.java | 52 +++++++-- .../com/google/gson/JsonObjectAsMapTest.java | 3 +- .../java/com/google/gson/MixedStreamTest.java | 4 +- .../JsonAdapterAnnotationOnClassesTest.java | 13 ++- .../gson/functional/JsonParserTest.java | 4 +- .../com/google/gson/functional/MapTest.java | 2 +- .../google/gson/functional/PrimitiveTest.java | 104 +++++++----------- .../ReflectionAccessFilterTest.java | 4 +- .../google/gson/functional/SecurityTest.java | 24 +++- .../internal/bind/JsonElementReaderTest.java | 2 +- .../internal/bind/util/ISO8601UtilsTest.java | 4 +- .../google/gson/stream/JsonReaderTest.java | 48 ++++---- .../google/gson/stream/JsonWriterTest.java | 17 ++- .../functional/ProtosWithAnnotationsTest.java | 14 ++- 15 files changed, 174 insertions(+), 129 deletions(-) diff --git a/extras/src/test/java/com/google/gson/interceptors/InterceptorTest.java b/extras/src/test/java/com/google/gson/interceptors/InterceptorTest.java index e6eae834df..6c5cc91fa6 100644 --- a/extras/src/test/java/com/google/gson/interceptors/InterceptorTest.java +++ b/extras/src/test/java/com/google/gson/interceptors/InterceptorTest.java @@ -85,9 +85,11 @@ public void testCollection() { @Test public void testMapKeyAndValues() { Type mapType = new TypeToken>() {}.getType(); - assertThrows( - JsonSyntaxException.class, - () -> gson.fromJson("[[{name:'bob',password:'pwd'},{}]]", mapType)); + var e = + assertThrows( + JsonSyntaxException.class, + () -> gson.fromJson("[[{name:'bob',password:'pwd'},{}]]", mapType)); + assertThat(e).hasMessageThat().isEqualTo("Address city, state and zip are required fields."); Map map = gson.fromJson( diff --git a/extras/src/test/java/com/google/gson/typeadapters/RuntimeTypeAdapterFactoryTest.java b/extras/src/test/java/com/google/gson/typeadapters/RuntimeTypeAdapterFactoryTest.java index 5a7ed29ffb..dc8bd495fb 100644 --- a/extras/src/test/java/com/google/gson/typeadapters/RuntimeTypeAdapterFactoryTest.java +++ b/extras/src/test/java/com/google/gson/typeadapters/RuntimeTypeAdapterFactoryTest.java @@ -130,9 +130,16 @@ public void testDeserializeMissingTypeField() { TypeAdapterFactory billingAdapter = RuntimeTypeAdapterFactory.of(BillingInstrument.class).registerSubtype(CreditCard.class); Gson gson = new GsonBuilder().registerTypeAdapterFactory(billingAdapter).create(); - assertThrows( - JsonParseException.class, - () -> gson.fromJson("{ownerName:'Jesse'}", BillingInstrument.class)); + var e = + assertThrows( + JsonParseException.class, + () -> gson.fromJson("{ownerName:'Jesse'}", BillingInstrument.class)); + assertThat(e) + .hasMessageThat() + .isEqualTo( + "cannot deserialize " + + BillingInstrument.class + + " because it does not define a field named type"); } @Test @@ -140,9 +147,16 @@ public void testDeserializeMissingSubtype() { TypeAdapterFactory billingAdapter = RuntimeTypeAdapterFactory.of(BillingInstrument.class).registerSubtype(BankTransfer.class); Gson gson = new GsonBuilder().registerTypeAdapterFactory(billingAdapter).create(); - assertThrows( - JsonParseException.class, - () -> gson.fromJson("{type:'CreditCard',ownerName:'Jesse'}", BillingInstrument.class)); + var e = + assertThrows( + JsonParseException.class, + () -> gson.fromJson("{type:'CreditCard',ownerName:'Jesse'}", BillingInstrument.class)); + assertThat(e) + .hasMessageThat() + .isEqualTo( + "cannot deserialize " + + BillingInstrument.class + + " subtype named CreditCard; did you forget to register a subtype?"); } @Test @@ -150,9 +164,16 @@ public void testSerializeMissingSubtype() { TypeAdapterFactory billingAdapter = RuntimeTypeAdapterFactory.of(BillingInstrument.class).registerSubtype(BankTransfer.class); Gson gson = new GsonBuilder().registerTypeAdapterFactory(billingAdapter).create(); - assertThrows( - JsonParseException.class, - () -> gson.toJson(new CreditCard("Jesse", 456), BillingInstrument.class)); + var e = + assertThrows( + JsonParseException.class, + () -> gson.toJson(new CreditCard("Jesse", 456), BillingInstrument.class)); + assertThat(e) + .hasMessageThat() + .isEqualTo( + "cannot serialize " + + CreditCard.class.getName() + + "; did you forget to register a subtype?"); } @Test @@ -161,9 +182,16 @@ public void testSerializeCollidingTypeFieldName() { RuntimeTypeAdapterFactory.of(BillingInstrument.class, "cvv") .registerSubtype(CreditCard.class); Gson gson = new GsonBuilder().registerTypeAdapterFactory(billingAdapter).create(); - assertThrows( - JsonParseException.class, - () -> gson.toJson(new CreditCard("Jesse", 456), BillingInstrument.class)); + var e = + assertThrows( + JsonParseException.class, + () -> gson.toJson(new CreditCard("Jesse", 456), BillingInstrument.class)); + assertThat(e) + .hasMessageThat() + .isEqualTo( + "cannot serialize " + + CreditCard.class.getName() + + " because it already defines a field named cvv"); } @Test diff --git a/gson/src/test/java/com/google/gson/JsonObjectAsMapTest.java b/gson/src/test/java/com/google/gson/JsonObjectAsMapTest.java index 0d7a5164e8..cdaca0b516 100644 --- a/gson/src/test/java/com/google/gson/JsonObjectAsMapTest.java +++ b/gson/src/test/java/com/google/gson/JsonObjectAsMapTest.java @@ -227,9 +227,10 @@ public void testEntrySet() { // Should contain entries in same order assertThat(new ArrayList<>(entrySet)).isEqualTo(expectedEntrySet); + // Entry set doesn't support insertions assertThrows( UnsupportedOperationException.class, - () -> entrySet.add(new SimpleEntry("c", new JsonPrimitive(3)))); + () -> entrySet.add(new SimpleEntry<>("c", new JsonPrimitive(3)))); assertThat(entrySet.remove(new SimpleEntry<>("a", new JsonPrimitive(1)))).isTrue(); assertThat(map.entrySet()) diff --git a/gson/src/test/java/com/google/gson/MixedStreamTest.java b/gson/src/test/java/com/google/gson/MixedStreamTest.java index e3d2fa03c8..d65b36bb61 100644 --- a/gson/src/test/java/com/google/gson/MixedStreamTest.java +++ b/gson/src/test/java/com/google/gson/MixedStreamTest.java @@ -82,7 +82,7 @@ public void testReadMixedStreamed() throws IOException { @SuppressWarnings("deprecation") // for JsonReader.setLenient @Test - public void testReaderDoesNotMutateState() throws IOException { + public void testReadDoesNotMutateState() throws IOException { Gson gson = new Gson(); JsonReader jsonReader = new JsonReader(new StringReader(CARS_JSON)); jsonReader.beginArray(); @@ -100,7 +100,7 @@ public void testReaderDoesNotMutateState() throws IOException { @SuppressWarnings("deprecation") // for JsonWriter.setLenient @Test - public void testWriterDoesNotMutateState() throws IOException { + public void testWriteDoesNotMutateState() throws IOException { Gson gson = new Gson(); JsonWriter jsonWriter = new JsonWriter(new StringWriter()); jsonWriter.beginArray(); diff --git a/gson/src/test/java/com/google/gson/functional/JsonAdapterAnnotationOnClassesTest.java b/gson/src/test/java/com/google/gson/functional/JsonAdapterAnnotationOnClassesTest.java index a4c7b476a4..97febb8367 100644 --- a/gson/src/test/java/com/google/gson/functional/JsonAdapterAnnotationOnClassesTest.java +++ b/gson/src/test/java/com/google/gson/functional/JsonAdapterAnnotationOnClassesTest.java @@ -372,12 +372,19 @@ public Foo read(JsonReader in) throws IOException { @Test public void testIncorrectJsonAdapterType() { Gson gson = new Gson(); - D obj = new D(); - assertThrows(IllegalArgumentException.class, () -> gson.toJson(obj)); + WithInvalidAdapterClass obj = new WithInvalidAdapterClass(); + var e = assertThrows(IllegalArgumentException.class, () -> gson.toJson(obj)); + assertThat(e) + .hasMessageThat() + .isEqualTo( + "Invalid attempt to bind an instance of java.lang.Integer as a @JsonAdapter for " + + WithInvalidAdapterClass.class.getName() + + ". @JsonAdapter value must be a TypeAdapter, TypeAdapterFactory, JsonSerializer" + + " or JsonDeserializer."); } @JsonAdapter(Integer.class) - private static final class D { + private static final class WithInvalidAdapterClass { @SuppressWarnings("unused") final String value = "a"; } diff --git a/gson/src/test/java/com/google/gson/functional/JsonParserTest.java b/gson/src/test/java/com/google/gson/functional/JsonParserTest.java index d6225fc5b4..57f6a887ed 100644 --- a/gson/src/test/java/com/google/gson/functional/JsonParserTest.java +++ b/gson/src/test/java/com/google/gson/functional/JsonParserTest.java @@ -75,7 +75,7 @@ public void testBadTypeForDeserializingCustomTree() { obj.addProperty("intValue", 11); JsonArray array = new JsonArray(); array.add(obj); - // BagOfPrimitives is not an array + // BagOfPrimitives should not be an array assertThrows(JsonParseException.class, () -> gson.fromJson(array, BagOfPrimitives.class)); } @@ -137,6 +137,6 @@ public void testExtraCommasInMaps() { assertThat(e) .hasCauseThat() .hasMessageThat() - .startsWith("Expected name at line 1 column 7 path $."); + .startsWith("Expected name at line 1 column 7 path $.\n"); } } diff --git a/gson/src/test/java/com/google/gson/functional/MapTest.java b/gson/src/test/java/com/google/gson/functional/MapTest.java index 0bb9969ede..689bbedc2d 100644 --- a/gson/src/test/java/com/google/gson/functional/MapTest.java +++ b/gson/src/test/java/com/google/gson/functional/MapTest.java @@ -581,7 +581,7 @@ public void testComplexKeysDeserialization() { assertThat(e) .hasCauseThat() .hasMessageThat() - .startsWith("Expected BEGIN_OBJECT but was STRING at line 1 column 3 path $"); + .startsWith("Expected BEGIN_OBJECT but was STRING at line 1 column 3 path $.\n"); } @Test diff --git a/gson/src/test/java/com/google/gson/functional/PrimitiveTest.java b/gson/src/test/java/com/google/gson/functional/PrimitiveTest.java index bc491db13c..81cd894c0f 100644 --- a/gson/src/test/java/com/google/gson/functional/PrimitiveTest.java +++ b/gson/src/test/java/com/google/gson/functional/PrimitiveTest.java @@ -523,25 +523,21 @@ public void testMoreSpecificSerialization() { } private static String extractElementFromArray(String json) { - return json.substring(json.indexOf('[') + 1, json.indexOf(']')); + return json.substring(json.indexOf('[') + 1, json.lastIndexOf(']')); } @Test public void testDoubleNaNSerializationNotSupportedByDefault() { + String expectedMessage = + "NaN is not a valid double value as per JSON specification. To override this behavior," + + " use GsonBuilder.serializeSpecialFloatingPointValues() method."; + var e = assertThrows(IllegalArgumentException.class, () -> gson.toJson(Double.NaN, double.class)); - assertThat(e) - .hasMessageThat() - .isEqualTo( - "NaN is not a valid double value as per JSON specification. To override this behavior," - + " use GsonBuilder.serializeSpecialFloatingPointValues() method."); + assertThat(e).hasMessageThat().isEqualTo(expectedMessage); e = assertThrows(IllegalArgumentException.class, () -> gson.toJson(Double.NaN, Double.class)); - assertThat(e) - .hasMessageThat() - .isEqualTo( - "NaN is not a valid double value as per JSON specification. To override this behavior," - + " use GsonBuilder.serializeSpecialFloatingPointValues() method."); + assertThat(e).hasMessageThat().isEqualTo(expectedMessage); } @Test @@ -559,19 +555,15 @@ public void testDoubleNaNDeserialization() { @Test public void testFloatNaNSerializationNotSupportedByDefault() { + String expectedMessage = + "NaN is not a valid double value as per JSON specification. To override this behavior," + + " use GsonBuilder.serializeSpecialFloatingPointValues() method."; + var e = assertThrows(IllegalArgumentException.class, () -> gson.toJson(Float.NaN, float.class)); - assertThat(e) - .hasMessageThat() - .isEqualTo( - "NaN is not a valid double value as per JSON specification. To override this behavior," - + " use GsonBuilder.serializeSpecialFloatingPointValues() method."); + assertThat(e).hasMessageThat().isEqualTo(expectedMessage); e = assertThrows(IllegalArgumentException.class, () -> gson.toJson(Float.NaN, Float.class)); - assertThat(e) - .hasMessageThat() - .isEqualTo( - "NaN is not a valid double value as per JSON specification. To override this behavior," - + " use GsonBuilder.serializeSpecialFloatingPointValues() method."); + assertThat(e).hasMessageThat().isEqualTo(expectedMessage); } @Test @@ -589,31 +581,27 @@ public void testFloatNaNDeserialization() { @Test public void testBigDecimalNaNDeserializationNotSupported() { - // Gson should not accept NaN for deserialization by default + // Gson should not accept NaN for deserialization of BigDecimal assertThrows(JsonSyntaxException.class, () -> gson.fromJson("NaN", BigDecimal.class)); } @Test public void testDoubleInfinitySerializationNotSupportedByDefault() { + String expectedMessage = + "Infinity is not a valid double value as per JSON specification. To override this" + + " behavior, use GsonBuilder.serializeSpecialFloatingPointValues() method."; + var e = assertThrows( IllegalArgumentException.class, () -> gson.toJson(Double.POSITIVE_INFINITY, double.class)); - assertThat(e) - .hasMessageThat() - .isEqualTo( - "Infinity is not a valid double value as per JSON specification. To override this" - + " behavior, use GsonBuilder.serializeSpecialFloatingPointValues() method."); + assertThat(e).hasMessageThat().isEqualTo(expectedMessage); e = assertThrows( IllegalArgumentException.class, () -> gson.toJson(Double.POSITIVE_INFINITY, Double.class)); - assertThat(e) - .hasMessageThat() - .isEqualTo( - "Infinity is not a valid double value as per JSON specification. To override this" - + " behavior, use GsonBuilder.serializeSpecialFloatingPointValues() method."); + assertThat(e).hasMessageThat().isEqualTo(expectedMessage); } @Test @@ -631,25 +619,21 @@ public void testDoubleInfinityDeserialization() { @Test public void testFloatInfinitySerializationNotSupportedByDefault() { + String expectedMessage = + "Infinity is not a valid double value as per JSON specification. To override this" + + " behavior, use GsonBuilder.serializeSpecialFloatingPointValues() method."; + var e = assertThrows( IllegalArgumentException.class, () -> gson.toJson(Float.POSITIVE_INFINITY, float.class)); - assertThat(e) - .hasMessageThat() - .isEqualTo( - "Infinity is not a valid double value as per JSON specification. To override this" - + " behavior, use GsonBuilder.serializeSpecialFloatingPointValues() method."); + assertThat(e).hasMessageThat().isEqualTo(expectedMessage); e = assertThrows( IllegalArgumentException.class, () -> gson.toJson(Float.POSITIVE_INFINITY, Float.class)); - assertThat(e) - .hasMessageThat() - .isEqualTo( - "Infinity is not a valid double value as per JSON specification. To override this" - + " behavior, use GsonBuilder.serializeSpecialFloatingPointValues() method."); + assertThat(e).hasMessageThat().isEqualTo(expectedMessage); } @Test @@ -667,31 +651,27 @@ public void testFloatInfinityDeserialization() { @Test public void testBigDecimalInfinityDeserializationNotSupported() { - // Gson should not accept positive infinity for deserialization with BigDecimal + // Gson should not accept positive infinity for deserialization of BigDecimal assertThrows(JsonSyntaxException.class, () -> gson.fromJson("Infinity", BigDecimal.class)); } @Test public void testNegativeInfinitySerializationNotSupportedByDefault() { + String expectedMessage = + "-Infinity is not a valid double value as per JSON specification. To override this" + + " behavior, use GsonBuilder.serializeSpecialFloatingPointValues() method."; + var e = assertThrows( IllegalArgumentException.class, () -> gson.toJson(Double.NEGATIVE_INFINITY, double.class)); - assertThat(e) - .hasMessageThat() - .isEqualTo( - "-Infinity is not a valid double value as per JSON specification. To override this" - + " behavior, use GsonBuilder.serializeSpecialFloatingPointValues() method."); + assertThat(e).hasMessageThat().isEqualTo(expectedMessage); e = assertThrows( IllegalArgumentException.class, () -> gson.toJson(Double.NEGATIVE_INFINITY, Double.class)); - assertThat(e) - .hasMessageThat() - .isEqualTo( - "-Infinity is not a valid double value as per JSON specification. To override this" - + " behavior, use GsonBuilder.serializeSpecialFloatingPointValues() method."); + assertThat(e).hasMessageThat().isEqualTo(expectedMessage); } @Test @@ -709,25 +689,21 @@ public void testNegativeInfinityDeserialization() { @Test public void testNegativeInfinityFloatSerializationNotSupportedByDefault() { + String expectedMessage = + "-Infinity is not a valid double value as per JSON specification. To override this" + + " behavior, use GsonBuilder.serializeSpecialFloatingPointValues() method."; + var e = assertThrows( IllegalArgumentException.class, () -> gson.toJson(Float.NEGATIVE_INFINITY, float.class)); - assertThat(e) - .hasMessageThat() - .isEqualTo( - "-Infinity is not a valid double value as per JSON specification. To override this" - + " behavior, use GsonBuilder.serializeSpecialFloatingPointValues() method."); + assertThat(e).hasMessageThat().isEqualTo(expectedMessage); e = assertThrows( IllegalArgumentException.class, () -> gson.toJson(Float.NEGATIVE_INFINITY, Float.class)); - assertThat(e) - .hasMessageThat() - .isEqualTo( - "-Infinity is not a valid double value as per JSON specification. To override this" - + " behavior, use GsonBuilder.serializeSpecialFloatingPointValues() method."); + assertThat(e).hasMessageThat().isEqualTo(expectedMessage); } @Test @@ -745,7 +721,7 @@ public void testNegativeInfinityFloatDeserialization() { @Test public void testBigDecimalNegativeInfinityDeserializationNotSupported() { - // Gson should not accept negative infinity for deserialization + // Gson should not accept negative infinity for deserialization of BigDecimal assertThrows(JsonSyntaxException.class, () -> gson.fromJson("-Infinity", BigDecimal.class)); } diff --git a/gson/src/test/java/com/google/gson/functional/ReflectionAccessFilterTest.java b/gson/src/test/java/com/google/gson/functional/ReflectionAccessFilterTest.java index 546c39e137..ce7dad2052 100644 --- a/gson/src/test/java/com/google/gson/functional/ReflectionAccessFilterTest.java +++ b/gson/src/test/java/com/google/gson/functional/ReflectionAccessFilterTest.java @@ -471,8 +471,8 @@ public FilterResult check(Class rawClass) { } /** - * When trying to deserialize interface an exception for that should be thrown, even if {@link - * FilterResult#BLOCK_INACCESSIBLE} is used + * When trying to deserialize interface, an exception for the missing adapter should be thrown, + * even if {@link FilterResult#BLOCK_INACCESSIBLE} is used. */ @Test public void testBlockInaccessibleInterface() { diff --git a/gson/src/test/java/com/google/gson/functional/SecurityTest.java b/gson/src/test/java/com/google/gson/functional/SecurityTest.java index 246ac1c794..a0a76188c5 100644 --- a/gson/src/test/java/com/google/gson/functional/SecurityTest.java +++ b/gson/src/test/java/com/google/gson/functional/SecurityTest.java @@ -44,7 +44,10 @@ public void setUp() throws Exception { public void testNonExecutableJsonSerialization() { Gson gson = gsonBuilder.generateNonExecutableJson().create(); String json = gson.toJson(new BagOfPrimitives()); - assertThat(json).startsWith(JSON_NON_EXECUTABLE_PREFIX); + assertThat(json) + .isEqualTo( + JSON_NON_EXECUTABLE_PREFIX + + "{\"longValue\":0,\"intValue\":0,\"booleanValue\":false,\"stringValue\":\"\"}"); } @Test @@ -59,7 +62,7 @@ public void testNonExecutableJsonDeserialization() { public void testJsonWithNonExectuableTokenSerialization() { Gson gson = gsonBuilder.generateNonExecutableJson().create(); String json = gson.toJson(JSON_NON_EXECUTABLE_PREFIX); - assertThat(json).contains(")]}'\n"); + assertThat(json).isEqualTo(JSON_NON_EXECUTABLE_PREFIX + "\")]}\\u0027\\n\""); } /** @@ -69,9 +72,12 @@ public void testJsonWithNonExectuableTokenSerialization() { @Test public void testJsonWithNonExectuableTokenWithRegularGsonDeserialization() { Gson gson = gsonBuilder.create(); - String json = JSON_NON_EXECUTABLE_PREFIX + "{stringValue:')]}\\u0027\\n'}"; + // Note: Embedding non-executable prefix literally is only possible because Gson is lenient by + // default + String json = + JSON_NON_EXECUTABLE_PREFIX + "{stringValue:\"" + JSON_NON_EXECUTABLE_PREFIX + "\"}"; BagOfPrimitives target = gson.fromJson(json, BagOfPrimitives.class); - assertThat(target.stringValue).isEqualTo(")]}'\n"); + assertThat(target.stringValue).isEqualTo(JSON_NON_EXECUTABLE_PREFIX); } /** @@ -82,9 +88,15 @@ public void testJsonWithNonExectuableTokenWithRegularGsonDeserialization() { public void testJsonWithNonExectuableTokenWithConfiguredGsonDeserialization() { // Gson should be able to deserialize a stream with non-exectuable token even if it is created Gson gson = gsonBuilder.generateNonExecutableJson().create(); - String json = JSON_NON_EXECUTABLE_PREFIX + "{intValue:2,stringValue:')]}\\u0027\\n'}"; + // Note: Embedding non-executable prefix literally is only possible because Gson is lenient by + // default + String json = + JSON_NON_EXECUTABLE_PREFIX + + "{intValue:2,stringValue:\"" + + JSON_NON_EXECUTABLE_PREFIX + + "\"}"; BagOfPrimitives target = gson.fromJson(json, BagOfPrimitives.class); - assertThat(target.stringValue).isEqualTo(")]}'\n"); + assertThat(target.stringValue).isEqualTo(JSON_NON_EXECUTABLE_PREFIX); assertThat(target.intValue).isEqualTo(2); } } diff --git a/gson/src/test/java/com/google/gson/internal/bind/JsonElementReaderTest.java b/gson/src/test/java/com/google/gson/internal/bind/JsonElementReaderTest.java index a1c182fcaf..d7786470ba 100644 --- a/gson/src/test/java/com/google/gson/internal/bind/JsonElementReaderTest.java +++ b/gson/src/test/java/com/google/gson/internal/bind/JsonElementReaderTest.java @@ -265,7 +265,7 @@ public void testNextJsonElement() throws IOException { 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()); + assertThat(reader.nextJsonElement()).isEqualTo(new JsonPrimitive(1)); assertThat(reader.nextName()).isEqualTo("B"); reader.beginObject(); diff --git a/gson/src/test/java/com/google/gson/internal/bind/util/ISO8601UtilsTest.java b/gson/src/test/java/com/google/gson/internal/bind/util/ISO8601UtilsTest.java index 7f2b3b20fa..e7a3e4d655 100644 --- a/gson/src/test/java/com/google/gson/internal/bind/util/ISO8601UtilsTest.java +++ b/gson/src/test/java/com/google/gson/internal/bind/util/ISO8601UtilsTest.java @@ -50,8 +50,8 @@ public void testDateFormatString() { calendar.set(2018, Calendar.JUNE, 25); Date date = calendar.getTime(); String dateStr = ISO8601Utils.format(date); - String expectedDate = "2018-06-25"; - assertThat(dateStr).startsWith(expectedDate); + String expectedDate = "2018-06-25T00:00:00Z"; + assertThat(dateStr).isEqualTo(expectedDate); } @Test diff --git a/gson/src/test/java/com/google/gson/stream/JsonReaderTest.java b/gson/src/test/java/com/google/gson/stream/JsonReaderTest.java index 0135e345db..3e62d33ac2 100644 --- a/gson/src/test/java/com/google/gson/stream/JsonReaderTest.java +++ b/gson/src/test/java/com/google/gson/stream/JsonReaderTest.java @@ -154,7 +154,7 @@ public void testCapitalizedTrueFailWhenStrict() { .hasMessageThat() .startsWith( "Use JsonReader.setStrictness(Strictness.LENIENT) to accept malformed JSON" - + " at line 1 column 1 path $"); + + " at line 1 column 1 path $\n"); reader = new JsonReader(reader("True")); reader.setStrictness(Strictness.STRICT); @@ -164,7 +164,7 @@ public void testCapitalizedTrueFailWhenStrict() { .hasMessageThat() .startsWith( "Use JsonReader.setStrictness(Strictness.LENIENT) to accept malformed JSON" - + " at line 1 column 1 path $"); + + " at line 1 column 1 path $\n"); } @Test @@ -177,7 +177,7 @@ public void testCapitalizedFalseFailWhenStrict() { .hasMessageThat() .startsWith( "Use JsonReader.setStrictness(Strictness.LENIENT) to accept malformed JSON" - + " at line 1 column 1 path $"); + + " at line 1 column 1 path $\n"); reader = new JsonReader(reader("FaLse")); reader.setStrictness(Strictness.STRICT); @@ -187,7 +187,7 @@ public void testCapitalizedFalseFailWhenStrict() { .hasMessageThat() .startsWith( "Use JsonReader.setStrictness(Strictness.LENIENT) to accept malformed JSON" - + " at line 1 column 1 path $"); + + " at line 1 column 1 path $\n"); } @Test @@ -200,7 +200,7 @@ public void testCapitalizedNullFailWhenStrict() { .hasMessageThat() .startsWith( "Use JsonReader.setStrictness(Strictness.LENIENT) to accept malformed JSON" - + " at line 1 column 1 path $"); + + " at line 1 column 1 path $\n"); reader = new JsonReader(reader("nulL")); reader.setStrictness(Strictness.STRICT); @@ -210,7 +210,7 @@ public void testCapitalizedNullFailWhenStrict() { .hasMessageThat() .startsWith( "Use JsonReader.setStrictness(Strictness.LENIENT) to accept malformed JSON" - + " at line 1 column 1 path $"); + + " at line 1 column 1 path $\n"); } @Test @@ -737,29 +737,28 @@ public void testLongs() throws IOException { } @Test - @Ignore( - "JsonReader advances after exception for invalid number was thrown; to be decided if that is" - + " acceptable") public void testNumberWithOctalPrefix() throws IOException { - String json = "[01]"; - JsonReader reader = new JsonReader(reader(json)); - reader.beginArray(); + String number = "01"; + String expectedLocation = "line 1 column 1 path $"; - var e = assertThrows(MalformedJsonException.class, () -> reader.peek()); - assertStrictError(e, "line 1 column 2 path $[0]"); + var e = assertThrows(MalformedJsonException.class, () -> new JsonReader(reader(number)).peek()); + assertStrictError(e, expectedLocation); - e = assertThrows(MalformedJsonException.class, () -> reader.nextInt()); - assertStrictError(e, "TODO"); + e = assertThrows(MalformedJsonException.class, () -> new JsonReader(reader(number)).nextInt()); + assertStrictError(e, expectedLocation); - e = assertThrows(MalformedJsonException.class, () -> reader.nextLong()); - assertStrictError(e, "TODO"); + e = assertThrows(MalformedJsonException.class, () -> new JsonReader(reader(number)).nextLong()); + assertStrictError(e, expectedLocation); - e = assertThrows(MalformedJsonException.class, () -> reader.nextDouble()); - assertStrictError(e, "TODO"); + e = + assertThrows( + MalformedJsonException.class, () -> new JsonReader(reader(number)).nextDouble()); + assertStrictError(e, expectedLocation); - assertThat(reader.nextString()).isEqualTo("01"); - reader.endArray(); - assertThat(reader.peek()).isEqualTo(JsonToken.END_DOCUMENT); + e = + assertThrows( + MalformedJsonException.class, () -> new JsonReader(reader(number)).nextString()); + assertStrictError(e, expectedLocation); } @Test @@ -1372,8 +1371,7 @@ 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 + // separators as implicit JSON null JsonReader reader = new JsonReader(reader("[true,,true]")); reader.beginArray(); diff --git a/gson/src/test/java/com/google/gson/stream/JsonWriterTest.java b/gson/src/test/java/com/google/gson/stream/JsonWriterTest.java index dd7d8f8db6..fd171e880f 100644 --- a/gson/src/test/java/com/google/gson/stream/JsonWriterTest.java +++ b/gson/src/test/java/com/google/gson/stream/JsonWriterTest.java @@ -873,10 +873,19 @@ public void testClosedWriterThrowsOnStructure() throws IOException { writer.beginArray(); writer.endArray(); writer.close(); - assertThrows(IllegalStateException.class, () -> writer.beginArray()); - assertThrows(IllegalStateException.class, () -> writer.endArray()); - assertThrows(IllegalStateException.class, () -> writer.beginObject()); - assertThrows(IllegalStateException.class, () -> writer.endObject()); + + String expectedMessage = "JsonWriter is closed."; + var e = assertThrows(IllegalStateException.class, () -> writer.beginArray()); + assertThat(e).hasMessageThat().isEqualTo(expectedMessage); + + e = assertThrows(IllegalStateException.class, () -> writer.endArray()); + assertThat(e).hasMessageThat().isEqualTo(expectedMessage); + + e = assertThrows(IllegalStateException.class, () -> writer.beginObject()); + assertThat(e).hasMessageThat().isEqualTo(expectedMessage); + + e = assertThrows(IllegalStateException.class, () -> writer.endObject()); + assertThat(e).hasMessageThat().isEqualTo(expectedMessage); } @Test diff --git a/proto/src/test/java/com/google/gson/protobuf/functional/ProtosWithAnnotationsTest.java b/proto/src/test/java/com/google/gson/protobuf/functional/ProtosWithAnnotationsTest.java index 7399170a49..f66f54d6d5 100644 --- a/proto/src/test/java/com/google/gson/protobuf/functional/ProtosWithAnnotationsTest.java +++ b/proto/src/test/java/com/google/gson/protobuf/functional/ProtosWithAnnotationsTest.java @@ -165,7 +165,9 @@ public void testProtoWithAnnotations_deserializeUnknownEnumValue() { @Test public void testProtoWithAnnotations_deserializeUnrecognizedEnumValue() { String json = String.format("{ %n" + " \"content\":\"UNRECOGNIZED\"%n" + "}"); - assertThrows(JsonParseException.class, () -> gson.fromJson(json, InnerMessage.class)); + var e = assertThrows(JsonParseException.class, () -> gson.fromJson(json, InnerMessage.class)); + assertThat(e).hasMessageThat().isEqualTo("Error while parsing proto"); + assertThat(e).hasCauseThat().hasMessageThat().isEqualTo("Unrecognized enum name: UNRECOGNIZED"); } @Test @@ -183,6 +185,16 @@ public void testProtoWithAnnotations_deserializeWithEnumNumbers() { assertThat(rebuilt).isEqualTo("{\"content\":2}"); } + @Test + public void testProtoWithAnnotations_deserializeUnrecognizedEnumNumber() { + String json = String.format("{ %n" + " \"content\":\"99\"%n" + "}"); + var e = + assertThrows( + JsonParseException.class, () -> gsonWithEnumNumbers.fromJson(json, InnerMessage.class)); + assertThat(e).hasMessageThat().isEqualTo("Error while parsing proto"); + assertThat(e).hasCauseThat().hasMessageThat().isEqualTo("Unrecognized enum value: 99"); + } + @Test public void testProtoWithAnnotations_serialize() { ProtoWithAnnotations proto = From 5ef8a226dfa95b6f8f3ae2434d184579ba4a88ae Mon Sep 17 00:00:00 2001 From: Marcono1234 Date: Sat, 8 Jun 2024 00:24:06 +0200 Subject: [PATCH 7/7] Remove explicit type arguments from tests where they can be inferred This works because unlike the main sources the tests are compiled with Java 11. --- .../java/com/google/gson/GsonBuilderTest.java | 2 +- .../test/java/com/google/gson/GsonTest.java | 20 +++++++++---------- .../com/google/gson/GsonTypeAdapterTest.java | 2 +- .../com/google/gson/JsonArrayAsListTest.java | 11 ++++------ .../com/google/gson/JsonObjectAsMapTest.java | 9 +++------ .../gson/OverrideCoreTypeAdaptersTest.java | 4 ++-- .../java/com/google/gson/TypeAdapterTest.java | 4 ++-- .../functional/DelegateTypeAdapterTest.java | 2 +- .../gson/functional/FormattingStyleTest.java | 3 +-- .../gson/functional/InstanceCreatorTest.java | 4 ++-- .../JsonAdapterAnnotationOnClassesTest.java | 20 +++++++++---------- .../JsonAdapterAnnotationOnFieldsTest.java | 6 +++--- .../com/google/gson/functional/MapTest.java | 2 +- .../functional/ParameterizedTypesTest.java | 10 +++++----- ...ntimeTypeAdapterFactoryFunctionalTest.java | 2 +- .../functional/StreamingTypeAdaptersTest.java | 4 ++-- .../gson/functional/TreeTypeAdaptersTest.java | 2 +- .../functional/TypeAdapterPrecedenceTest.java | 6 +++--- .../functional/TypeHierarchyAdapterTest.java | 2 +- .../gson/functional/TypeVariableTest.java | 2 +- .../google/gson/reflect/TypeTokenTest.java | 2 +- 21 files changed, 55 insertions(+), 64 deletions(-) diff --git a/gson/src/test/java/com/google/gson/GsonBuilderTest.java b/gson/src/test/java/com/google/gson/GsonBuilderTest.java index 2d9a63101d..cbebb1d619 100644 --- a/gson/src/test/java/com/google/gson/GsonBuilderTest.java +++ b/gson/src/test/java/com/google/gson/GsonBuilderTest.java @@ -38,7 +38,7 @@ */ public class GsonBuilderTest { private static final TypeAdapter NULL_TYPE_ADAPTER = - new TypeAdapter() { + new TypeAdapter<>() { @Override public void write(JsonWriter out, Object value) { throw new AssertionError(); diff --git a/gson/src/test/java/com/google/gson/GsonTest.java b/gson/src/test/java/com/google/gson/GsonTest.java index e51259e781..8bfc69b45a 100644 --- a/gson/src/test/java/com/google/gson/GsonTest.java +++ b/gson/src/test/java/com/google/gson/GsonTest.java @@ -72,7 +72,7 @@ public void testOverridesDefaultExcluder() { new Gson( CUSTOM_EXCLUDER, CUSTOM_FIELD_NAMING_STRATEGY, - new HashMap>(), + new HashMap<>(), true, false, true, @@ -85,12 +85,12 @@ public void testOverridesDefaultExcluder() { null, DateFormat.DEFAULT, DateFormat.DEFAULT, - new ArrayList(), - new ArrayList(), - new ArrayList(), + new ArrayList<>(), + new ArrayList<>(), + new ArrayList<>(), CUSTOM_OBJECT_TO_NUMBER_STRATEGY, CUSTOM_NUMBER_TO_NUMBER_STRATEGY, - Collections.emptyList()); + Collections.emptyList()); assertThat(gson.excluder).isEqualTo(CUSTOM_EXCLUDER); assertThat(gson.fieldNamingStrategy()).isEqualTo(CUSTOM_FIELD_NAMING_STRATEGY); @@ -104,7 +104,7 @@ public void testClonedTypeAdapterFactoryListsAreIndependent() { new Gson( CUSTOM_EXCLUDER, CUSTOM_FIELD_NAMING_STRATEGY, - new HashMap>(), + new HashMap<>(), true, false, true, @@ -117,12 +117,12 @@ public void testClonedTypeAdapterFactoryListsAreIndependent() { null, DateFormat.DEFAULT, DateFormat.DEFAULT, - new ArrayList(), - new ArrayList(), - new ArrayList(), + new ArrayList<>(), + new ArrayList<>(), + new ArrayList<>(), CUSTOM_OBJECT_TO_NUMBER_STRATEGY, CUSTOM_NUMBER_TO_NUMBER_STRATEGY, - Collections.emptyList()); + Collections.emptyList()); Gson clone = original.newBuilder().registerTypeAdapter(int.class, new TestTypeAdapter()).create(); diff --git a/gson/src/test/java/com/google/gson/GsonTypeAdapterTest.java b/gson/src/test/java/com/google/gson/GsonTypeAdapterTest.java index fcf46238aa..5b4fb49907 100644 --- a/gson/src/test/java/com/google/gson/GsonTypeAdapterTest.java +++ b/gson/src/test/java/com/google/gson/GsonTypeAdapterTest.java @@ -152,7 +152,7 @@ private static void assertSerialized( boolean registerAbstractHierarchyDeserializer, Object instance) { JsonDeserializer deserializer = - new JsonDeserializer() { + new JsonDeserializer<>() { @Override public Abstract deserialize( JsonElement json, Type typeOfT, JsonDeserializationContext context) diff --git a/gson/src/test/java/com/google/gson/JsonArrayAsListTest.java b/gson/src/test/java/com/google/gson/JsonArrayAsListTest.java index 4f2577ce6c..a9a62eba1d 100644 --- a/gson/src/test/java/com/google/gson/JsonArrayAsListTest.java +++ b/gson/src/test/java/com/google/gson/JsonArrayAsListTest.java @@ -83,7 +83,7 @@ public void testAdd() { assertThat(list.add(JsonNull.INSTANCE)).isTrue(); List expectedList = - Arrays.asList( + Arrays.asList( new JsonPrimitive(2), new JsonPrimitive(3), new JsonPrimitive(1), @@ -111,21 +111,18 @@ public void testAddAll() { list.addAll(Arrays.asList(new JsonPrimitive(2), new JsonPrimitive(3))); List expectedList = - Arrays.asList( - new JsonPrimitive(1), new JsonPrimitive(2), new JsonPrimitive(3)); + Arrays.asList(new JsonPrimitive(1), new JsonPrimitive(2), new JsonPrimitive(3)); assertThat(list).isEqualTo(expectedList); assertThat(list).isEqualTo(expectedList); NullPointerException e = assertThrows( - NullPointerException.class, - () -> list.addAll(0, Collections.singletonList(null))); + NullPointerException.class, () -> list.addAll(0, Collections.singletonList(null))); assertThat(e).hasMessageThat().isEqualTo("Element must be non-null"); e = assertThrows( - NullPointerException.class, - () -> list.addAll(Collections.singletonList(null))); + NullPointerException.class, () -> list.addAll(Collections.singletonList(null))); assertThat(e).hasMessageThat().isEqualTo("Element must be non-null"); } diff --git a/gson/src/test/java/com/google/gson/JsonObjectAsMapTest.java b/gson/src/test/java/com/google/gson/JsonObjectAsMapTest.java index cdaca0b516..55d045cbe2 100644 --- a/gson/src/test/java/com/google/gson/JsonObjectAsMapTest.java +++ b/gson/src/test/java/com/google/gson/JsonObjectAsMapTest.java @@ -148,15 +148,12 @@ public void testPutAll() { var e = assertThrows( NullPointerException.class, - () -> - map.putAll( - Collections.singletonMap(null, new JsonPrimitive(1)))); + () -> map.putAll(Collections.singletonMap(null, new JsonPrimitive(1)))); assertThat(e).hasMessageThat().isEqualTo("key == null"); e = assertThrows( - NullPointerException.class, - () -> map.putAll(Collections.singletonMap("a", null))); + NullPointerException.class, () -> map.putAll(Collections.singletonMap("a", null))); assertThat(e).hasMessageThat().isEqualTo("value == null"); } @@ -221,7 +218,7 @@ public void testEntrySet() { Set> entrySet = map.entrySet(); List> expectedEntrySet = - Arrays.>asList( + Arrays.asList( new SimpleEntry<>("b", new JsonPrimitive(2)), new SimpleEntry<>("a", new JsonPrimitive(1))); // Should contain entries in same order diff --git a/gson/src/test/java/com/google/gson/OverrideCoreTypeAdaptersTest.java b/gson/src/test/java/com/google/gson/OverrideCoreTypeAdaptersTest.java index a34f35f0ca..134abe1571 100644 --- a/gson/src/test/java/com/google/gson/OverrideCoreTypeAdaptersTest.java +++ b/gson/src/test/java/com/google/gson/OverrideCoreTypeAdaptersTest.java @@ -31,7 +31,7 @@ */ public class OverrideCoreTypeAdaptersTest { private static final TypeAdapter booleanAsIntAdapter = - new TypeAdapter() { + new TypeAdapter<>() { @Override public void write(JsonWriter out, Boolean value) throws IOException { out.value(value ? 1 : 0); @@ -45,7 +45,7 @@ public Boolean read(JsonReader in) throws IOException { }; private static final TypeAdapter swapCaseStringAdapter = - new TypeAdapter() { + new TypeAdapter<>() { @Override public void write(JsonWriter out, String value) throws IOException { out.value(value.toUpperCase(Locale.US)); diff --git a/gson/src/test/java/com/google/gson/TypeAdapterTest.java b/gson/src/test/java/com/google/gson/TypeAdapterTest.java index 8a551adb85..e5aa8a422a 100644 --- a/gson/src/test/java/com/google/gson/TypeAdapterTest.java +++ b/gson/src/test/java/com/google/gson/TypeAdapterTest.java @@ -53,7 +53,7 @@ public String read(JsonReader in) { public void testToJson_ThrowingIOException() { final IOException exception = new IOException("test"); TypeAdapter adapter = - new TypeAdapter() { + new TypeAdapter<>() { @Override public void write(JsonWriter out, Integer value) throws IOException { throw exception; @@ -73,7 +73,7 @@ public Integer read(JsonReader in) { } private static final TypeAdapter adapter = - new TypeAdapter() { + new TypeAdapter<>() { @Override public void write(JsonWriter out, String value) throws IOException { out.value(value); diff --git a/gson/src/test/java/com/google/gson/functional/DelegateTypeAdapterTest.java b/gson/src/test/java/com/google/gson/functional/DelegateTypeAdapterTest.java index 99401266cb..8c837fa051 100644 --- a/gson/src/test/java/com/google/gson/functional/DelegateTypeAdapterTest.java +++ b/gson/src/test/java/com/google/gson/functional/DelegateTypeAdapterTest.java @@ -78,7 +78,7 @@ private static class StatsTypeAdapterFactory implements TypeAdapterFactory { @Override public TypeAdapter create(Gson gson, TypeToken type) { final TypeAdapter delegate = gson.getDelegateAdapter(this, type); - return new TypeAdapter() { + return new TypeAdapter<>() { @Override public void write(JsonWriter out, T value) throws IOException { ++numWrites; diff --git a/gson/src/test/java/com/google/gson/functional/FormattingStyleTest.java b/gson/src/test/java/com/google/gson/functional/FormattingStyleTest.java index fa07a3c9fd..581b23e55b 100644 --- a/gson/src/test/java/com/google/gson/functional/FormattingStyleTest.java +++ b/gson/src/test/java/com/google/gson/functional/FormattingStyleTest.java @@ -73,8 +73,7 @@ public void testDefault() { public void testVariousCombinationsParse() { // Mixing various indent and newline styles in the same string, to be parsed. String jsonStringMix = "{\r\t'a':\r\n[ 1,2\t]\n}"; - TypeToken>> inputType = - new TypeToken>>() {}; + TypeToken>> inputType = new TypeToken<>() {}; Map> actualParsed; // Test all that all combinations of newline can be parsed and generate the same INPUT. diff --git a/gson/src/test/java/com/google/gson/functional/InstanceCreatorTest.java b/gson/src/test/java/com/google/gson/functional/InstanceCreatorTest.java index 54a9fedce2..5a76b9f175 100644 --- a/gson/src/test/java/com/google/gson/functional/InstanceCreatorTest.java +++ b/gson/src/test/java/com/google/gson/functional/InstanceCreatorTest.java @@ -106,7 +106,7 @@ public void testInstanceCreatorForCollectionType() { @SuppressWarnings("serial") class SubArrayList extends ArrayList {} InstanceCreator> listCreator = - new InstanceCreator>() { + new InstanceCreator<>() { @Override public List createInstance(Type type) { return new SubArrayList<>(); @@ -124,7 +124,7 @@ public void testInstanceCreatorForParametrizedType() { @SuppressWarnings("serial") class SubTreeSet extends TreeSet {} InstanceCreator> sortedSetCreator = - new InstanceCreator>() { + new InstanceCreator<>() { @Override public SortedSet createInstance(Type type) { return new SubTreeSet<>(); diff --git a/gson/src/test/java/com/google/gson/functional/JsonAdapterAnnotationOnClassesTest.java b/gson/src/test/java/com/google/gson/functional/JsonAdapterAnnotationOnClassesTest.java index 97febb8367..081b869e93 100644 --- a/gson/src/test/java/com/google/gson/functional/JsonAdapterAnnotationOnClassesTest.java +++ b/gson/src/test/java/com/google/gson/functional/JsonAdapterAnnotationOnClassesTest.java @@ -78,7 +78,7 @@ public void testJsonAdapterFactoryInvoked() { @Test public void testRegisteredAdapterOverridesJsonAdapter() { TypeAdapter typeAdapter = - new TypeAdapter() { + new TypeAdapter<>() { @Override public void write(JsonWriter out, A value) throws IOException { out.value("registeredAdapter"); @@ -98,7 +98,7 @@ public A read(JsonReader in) throws IOException { @Test public void testRegisteredSerializerOverridesJsonAdapter() { JsonSerializer serializer = - new JsonSerializer() { + new JsonSerializer<>() { @Override public JsonElement serialize(A src, Type typeOfSrc, JsonSerializationContext context) { return new JsonPrimitive("registeredSerializer"); @@ -115,7 +115,7 @@ public JsonElement serialize(A src, Type typeOfSrc, JsonSerializationContext con @Test public void testRegisteredDeserializerOverridesJsonAdapter() { JsonDeserializer deserializer = - new JsonDeserializer() { + new JsonDeserializer<>() { @Override public A deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { @@ -170,8 +170,7 @@ public void testFactoryReturningNull() { assertThat(gson.fromJson("null", WithNullReturningFactory.class)).isNull(); assertThat(gson.toJson(null, WithNullReturningFactory.class)).isEqualTo("null"); - TypeToken> stringTypeArg = - new TypeToken>() {}; + TypeToken> stringTypeArg = new TypeToken<>() {}; WithNullReturningFactory deserialized = gson.fromJson("\"a\"", stringTypeArg); assertThat(deserialized.t).isEqualTo("custom-read:a"); assertThat(gson.fromJson("null", stringTypeArg)).isNull(); @@ -181,8 +180,7 @@ public void testFactoryReturningNull() { // Factory should return `null` for this type and Gson should fall back to reflection-based // adapter - TypeToken> numberTypeArg = - new TypeToken>() {}; + TypeToken> numberTypeArg = new TypeToken<>() {}; deserialized = gson.fromJson("{\"t\":1}", numberTypeArg); assertThat(deserialized.t).isEqualTo(1); assertThat(gson.toJson(new WithNullReturningFactory<>(2), numberTypeArg.getType())) @@ -266,7 +264,7 @@ private static class C { static final class JsonAdapterFactory implements TypeAdapterFactory { @Override public TypeAdapter create(Gson gson, final TypeToken type) { - return new TypeAdapter() { + return new TypeAdapter<>() { @Override public void write(JsonWriter out, T value) throws IOException { out.value("jsonAdapterFactory"); @@ -428,7 +426,7 @@ public TypeAdapter create(Gson gson, TypeToken type) { TypeAdapter delegate = gson.getDelegateAdapter(this, type); - return new TypeAdapter() { + return new TypeAdapter<>() { @Override public T read(JsonReader in) throws IOException { // Perform custom deserialization @@ -478,7 +476,7 @@ private static class WithDelayedDelegatingFactory { static class Factory implements TypeAdapterFactory { @Override public TypeAdapter create(Gson gson, TypeToken type) { - return new TypeAdapter() { + return new TypeAdapter<>() { // suppress Error Prone warning; should be clear that `Factory` refers to enclosing class @SuppressWarnings("SameNameButDifferent") private TypeAdapter delegate() { @@ -670,7 +668,7 @@ static class Factory implements TypeAdapterFactory { public TypeAdapter create(Gson gson, TypeToken type) { TypeAdapter delegate = gson.getDelegateAdapter(this, type); - return new TypeAdapter() { + return new TypeAdapter<>() { @Override public T read(JsonReader in) throws IOException { // Perform custom deserialization diff --git a/gson/src/test/java/com/google/gson/functional/JsonAdapterAnnotationOnFieldsTest.java b/gson/src/test/java/com/google/gson/functional/JsonAdapterAnnotationOnFieldsTest.java index a5d355f054..277babad74 100644 --- a/gson/src/test/java/com/google/gson/functional/JsonAdapterAnnotationOnFieldsTest.java +++ b/gson/src/test/java/com/google/gson/functional/JsonAdapterAnnotationOnFieldsTest.java @@ -147,7 +147,7 @@ public Part read(JsonReader in) throws IOException { private static class GizmoPartTypeAdapterFactory implements TypeAdapterFactory { @Override public TypeAdapter create(Gson gson, final TypeToken type) { - return new TypeAdapter() { + return new TypeAdapter<>() { @Override public void write(JsonWriter out, T value) throws IOException { out.value("GizmoPartTypeAdapterFactory"); @@ -303,7 +303,7 @@ private GadgetWithPrimitivePart(long part) { private static final class LongToStringTypeAdapterFactory implements TypeAdapterFactory { static final TypeAdapter ADAPTER = - new TypeAdapter() { + new TypeAdapter<>() { @Override public void write(JsonWriter out, Long value) throws IOException { out.value(value.toString()); @@ -352,7 +352,7 @@ private static final class Gizmo2 { private static class Gizmo2PartTypeAdapterFactory implements TypeAdapterFactory { @Override public TypeAdapter create(Gson gson, final TypeToken type) { - return new TypeAdapter() { + return new TypeAdapter<>() { @Override public void write(JsonWriter out, T value) throws IOException { out.value("GizmoPartTypeAdapterFactory"); diff --git a/gson/src/test/java/com/google/gson/functional/MapTest.java b/gson/src/test/java/com/google/gson/functional/MapTest.java index 689bbedc2d..293178c607 100644 --- a/gson/src/test/java/com/google/gson/functional/MapTest.java +++ b/gson/src/test/java/com/google/gson/functional/MapTest.java @@ -526,7 +526,7 @@ public final void testInterfaceTypeMapWithSerializer() { "{\"bases\":{\"Test\":" + baseTypeJson + "},\"subs\":{\"Test\":" + subTypeJson + "}}"; JsonSerializer baseTypeAdapter = - new JsonSerializer() { + new JsonSerializer<>() { @Override public JsonElement serialize( TestTypes.Base src, Type typeOfSrc, JsonSerializationContext context) { diff --git a/gson/src/test/java/com/google/gson/functional/ParameterizedTypesTest.java b/gson/src/test/java/com/google/gson/functional/ParameterizedTypesTest.java index 42e77840e3..b408544d5e 100644 --- a/gson/src/test/java/com/google/gson/functional/ParameterizedTypesTest.java +++ b/gson/src/test/java/com/google/gson/functional/ParameterizedTypesTest.java @@ -120,11 +120,11 @@ public void testParameterizedTypeWithCustomSerializer() { .create(); MyParameterizedType intTarget = new MyParameterizedType<>(10); String json = gson.toJson(intTarget, ptIntegerType); - assertThat(json).isEqualTo(MyParameterizedTypeAdapter.getExpectedJson(intTarget)); + assertThat(json).isEqualTo(MyParameterizedTypeAdapter.getExpectedJson(intTarget)); MyParameterizedType stringTarget = new MyParameterizedType<>("abc"); json = gson.toJson(stringTarget, ptStringType); - assertThat(json).isEqualTo(MyParameterizedTypeAdapter.getExpectedJson(stringTarget)); + assertThat(json).isEqualTo(MyParameterizedTypeAdapter.getExpectedJson(stringTarget)); } @Test @@ -140,12 +140,12 @@ public void testParameterizedTypesWithCustomDeserializer() { .create(); MyParameterizedType src = new MyParameterizedType<>(10); - String json = MyParameterizedTypeAdapter.getExpectedJson(src); + String json = MyParameterizedTypeAdapter.getExpectedJson(src); MyParameterizedType intTarget = gson.fromJson(json, ptIntegerType); assertThat(intTarget.value).isEqualTo(10); MyParameterizedType srcStr = new MyParameterizedType<>("abc"); - json = MyParameterizedTypeAdapter.getExpectedJson(srcStr); + json = MyParameterizedTypeAdapter.getExpectedJson(srcStr); MyParameterizedType stringTarget = gson.fromJson(json, ptStringType); assertThat(stringTarget.value).isEqualTo("abc"); } @@ -515,7 +515,7 @@ private static void assertCorrectlyDeserialized(Object object) { @Test public void testGsonFromJsonTypeToken() { - TypeToken> typeToken = new TypeToken>() {}; + TypeToken> typeToken = new TypeToken<>() {}; Type type = typeToken.getType(); { diff --git a/gson/src/test/java/com/google/gson/functional/RuntimeTypeAdapterFactoryFunctionalTest.java b/gson/src/test/java/com/google/gson/functional/RuntimeTypeAdapterFactoryFunctionalTest.java index 667d231f36..3fae2da586 100644 --- a/gson/src/test/java/com/google/gson/functional/RuntimeTypeAdapterFactoryFunctionalTest.java +++ b/gson/src/test/java/com/google/gson/functional/RuntimeTypeAdapterFactoryFunctionalTest.java @@ -174,7 +174,7 @@ public TypeAdapter create(Gson gson, TypeToken type) { subtypeToDelegate.put(entry.getValue(), delegate); } - return new TypeAdapter() { + return new TypeAdapter<>() { @Override public R read(JsonReader in) { JsonElement jsonElement = Streams.parse(in); diff --git a/gson/src/test/java/com/google/gson/functional/StreamingTypeAdaptersTest.java b/gson/src/test/java/com/google/gson/functional/StreamingTypeAdaptersTest.java index f7bdf3bb14..c6245cb27a 100644 --- a/gson/src/test/java/com/google/gson/functional/StreamingTypeAdaptersTest.java +++ b/gson/src/test/java/com/google/gson/functional/StreamingTypeAdaptersTest.java @@ -118,7 +118,7 @@ public void testDeserializeWithCustomTypeAdapter() throws IOException { private void usePersonNameAdapter() { TypeAdapter personNameAdapter = - new TypeAdapter() { + new TypeAdapter<>() { @Override public Person read(JsonReader in) throws IOException { String name = in.nextString(); @@ -181,7 +181,7 @@ public void testDeserialize2dArray() throws IOException { @Test public void testNullSafe() { TypeAdapter typeAdapter = - new TypeAdapter() { + new TypeAdapter<>() { @Override public Person read(JsonReader in) throws IOException { List values = Splitter.on(',').splitToList(in.nextString()); diff --git a/gson/src/test/java/com/google/gson/functional/TreeTypeAdaptersTest.java b/gson/src/test/java/com/google/gson/functional/TreeTypeAdaptersTest.java index 2aa043f424..6e9debbb0c 100644 --- a/gson/src/test/java/com/google/gson/functional/TreeTypeAdaptersTest.java +++ b/gson/src/test/java/com/google/gson/functional/TreeTypeAdaptersTest.java @@ -141,7 +141,7 @@ private static class Course { private final Assignment assignment; private Course() { - this(null, 0, null, new ArrayList()); + this(null, 0, null, new ArrayList<>()); } public Course( diff --git a/gson/src/test/java/com/google/gson/functional/TypeAdapterPrecedenceTest.java b/gson/src/test/java/com/google/gson/functional/TypeAdapterPrecedenceTest.java index 0252ec5052..52d04d9ba2 100644 --- a/gson/src/test/java/com/google/gson/functional/TypeAdapterPrecedenceTest.java +++ b/gson/src/test/java/com/google/gson/functional/TypeAdapterPrecedenceTest.java @@ -140,7 +140,7 @@ private Foo(String name) { } private static JsonSerializer newSerializer(final String name) { - return new JsonSerializer() { + return new JsonSerializer<>() { @Override public JsonElement serialize(Foo src, Type typeOfSrc, JsonSerializationContext context) { return new JsonPrimitive(src.name + " via " + name); @@ -149,7 +149,7 @@ public JsonElement serialize(Foo src, Type typeOfSrc, JsonSerializationContext c } private static JsonDeserializer newDeserializer(final String name) { - return new JsonDeserializer() { + return new JsonDeserializer<>() { @Override public Foo deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) { return new Foo(json.getAsString() + " via " + name); @@ -158,7 +158,7 @@ public Foo deserialize(JsonElement json, Type typeOfT, JsonDeserializationContex } private static TypeAdapter newTypeAdapter(final String name) { - return new TypeAdapter() { + return new TypeAdapter<>() { @Override public Foo read(JsonReader in) throws IOException { return new Foo(in.nextString() + " via " + name); diff --git a/gson/src/test/java/com/google/gson/functional/TypeHierarchyAdapterTest.java b/gson/src/test/java/com/google/gson/functional/TypeHierarchyAdapterTest.java index 973afb04ac..151863deef 100644 --- a/gson/src/test/java/com/google/gson/functional/TypeHierarchyAdapterTest.java +++ b/gson/src/test/java/com/google/gson/functional/TypeHierarchyAdapterTest.java @@ -201,7 +201,7 @@ public Employee deserialize(JsonElement json, Type typeOfT, JsonDeserializationC result = new Employee(); } result.userid = context.deserialize(object.get("userid"), String.class); - result.startDate = context.deserialize(object.get("startDate"), long.class); + result.startDate = context.deserialize(object.get("startDate"), long.class); return result; } } diff --git a/gson/src/test/java/com/google/gson/functional/TypeVariableTest.java b/gson/src/test/java/com/google/gson/functional/TypeVariableTest.java index d1076fdb15..af1957e159 100644 --- a/gson/src/test/java/com/google/gson/functional/TypeVariableTest.java +++ b/gson/src/test/java/com/google/gson/functional/TypeVariableTest.java @@ -43,7 +43,7 @@ public void testAdvancedTypeVariables() { arrayList.add(2); arrayList.add(3); bar1.map.put("key1", arrayList); - bar1.map.put("key2", new ArrayList()); + bar1.map.put("key2", new ArrayList<>()); String json = gson.toJson(bar1); Bar bar2 = gson.fromJson(json, Bar.class); diff --git a/gson/src/test/java/com/google/gson/reflect/TypeTokenTest.java b/gson/src/test/java/com/google/gson/reflect/TypeTokenTest.java index fa3a7a0ed7..d0e13805cd 100644 --- a/gson/src/test/java/com/google/gson/reflect/TypeTokenTest.java +++ b/gson/src/test/java/com/google/gson/reflect/TypeTokenTest.java @@ -328,7 +328,7 @@ class SubSubTypeToken2 extends SubTypeToken {} } private static void createTypeTokenTypeVariable() { - TypeToken unused = new TypeToken() {}; + var unused = new TypeToken() {}; } /**