Merge pull request #1909 from HiFromAjay/aj

Test cases for testing the exceptional behavior of JsonArray get... methods
This commit is contained in:
Éamonn McManus 2021-08-07 07:54:12 -07:00 committed by GitHub
commit 9edaeb3b2e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -16,9 +16,8 @@
package com.google.gson;
import junit.framework.TestCase;
import com.google.gson.common.MoreAsserts;
import junit.framework.TestCase;
/**
* @author Jesse Wilson
@ -99,4 +98,68 @@ public final class JsonArrayTest extends TestCase {
assertEquals(1, original.get(0).getAsJsonArray().size());
assertEquals(0, copy.get(0).getAsJsonArray().size());
}
public void testFailedGetArrayValues() {
JsonArray jsonArray = new JsonArray();
jsonArray.add(JsonParser.parseString("{" + "\"key1\":\"value1\"," + "\"key2\":\"value2\"," + "\"key3\":\"value3\"," + "\"key4\":\"value4\"" + "}"));
try {
jsonArray.getAsBoolean();
fail("expected getBoolean to fail");
} catch (UnsupportedOperationException e) {
assertEquals("Expected an exception message",
"JsonObject", e.getMessage());
}
try {
jsonArray.get(-1);
fail("expected get to fail");
} catch (IndexOutOfBoundsException e) {
assertEquals("Expected an exception message",
"Index -1 out of bounds for length 1", e.getMessage());
}
try {
jsonArray.getAsString();
fail("expected getString to fail");
} catch (UnsupportedOperationException e) {
assertEquals("Expected an exception message",
"JsonObject", e.getMessage());
}
jsonArray.remove(0);
jsonArray.add("hello");
try {
jsonArray.getAsDouble();
fail("expected getDouble to fail");
} catch (NumberFormatException e) {
assertEquals("Expected an exception message",
"For input string: \"hello\"", e.getMessage());
}
try {
jsonArray.getAsInt();
fail("expected getInt to fail");
} catch (NumberFormatException e) {
assertEquals("Expected an exception message",
"For input string: \"hello\"", e.getMessage());
}
try {
jsonArray.get(0).getAsJsonArray();
fail("expected getJSONArray to fail");
} catch (IllegalStateException e) {
assertEquals("Expected an exception message",
"Not a JSON Array: \"hello\"", e.getMessage());
}
try {
jsonArray.getAsJsonObject();
fail("expected getJSONObject to fail");
} catch (IllegalStateException e) {
assertEquals("Expected an exception message",
"Not a JSON Object: [\"hello\"]", e.getMessage());
}
try {
jsonArray.getAsLong();
fail("expected getLong to fail");
} catch (NumberFormatException e) {
assertEquals("Expected an exception message",
"For input string: \"hello\"", e.getMessage());
}
}
}