Skip to content

Commit

Permalink
Merge pull request #1909 from HiFromAjay/aj
Browse files Browse the repository at this point in the history
Test cases for testing the exceptional behavior of JsonArray get... methods
  • Loading branch information
eamonnmcmanus committed Aug 7, 2021
2 parents 789818d + 01ab13f commit 9edaeb3
Showing 1 changed file with 65 additions and 2 deletions.
67 changes: 65 additions & 2 deletions gson/src/test/java/com/google/gson/JsonArrayTest.java
Expand Up @@ -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
Expand Down Expand Up @@ -99,4 +98,68 @@ public void testDeepCopy() {
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());
}
}
}

0 comments on commit 9edaeb3

Please sign in to comment.