diff --git a/gson/src/test/java/com/google/gson/JsonArrayTest.java b/gson/src/test/java/com/google/gson/JsonArrayTest.java index b77d6f1b44..3975ce2c84 100644 --- a/gson/src/test/java/com/google/gson/JsonArrayTest.java +++ b/gson/src/test/java/com/google/gson/JsonArrayTest.java @@ -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 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()); + } + } }