From ae77b5cd83121555152a13407fce230992afc0c0 Mon Sep 17 00:00:00 2001 From: Nicholas Cull Date: Sat, 23 Jul 2016 22:51:50 +1000 Subject: [PATCH] Tests for deep copy and mutability of toList() and toMap(). Both toMap() and toList() return deep copies, which are also mutable. That is, any changes to the JSONObject or JSONArray do not affect the newly create Map or List, and vice-versa. The resulting objects can be altered. --- src/test/java/org/json/junit/JSONArrayTest.java | 8 ++++++++ src/test/java/org/json/junit/JSONObjectTest.java | 9 +++++++++ 2 files changed, 17 insertions(+) diff --git a/src/test/java/org/json/junit/JSONArrayTest.java b/src/test/java/org/json/junit/JSONArrayTest.java index c818e8b..9f0e773 100644 --- a/src/test/java/org/json/junit/JSONArrayTest.java +++ b/src/test/java/org/json/junit/JSONArrayTest.java @@ -920,5 +920,13 @@ public class JSONArrayTest { assertTrue("val3 list val 2 should not be null", val3Val2List != null); assertTrue("val3 list val 2 should have 1 element", val3Val2List.size() == 1); assertTrue("val3 list val 2 list element 1 should be null", val3Val2List.get(0) == null); + + // assert that toList() is a deep copy + jsonArray.getJSONObject(1).put("key1", "still val1"); + assertTrue("val2 map key 1 should be val1", val2Map.get("key1").equals("val1")); + + // assert that the new list is mutable + assertTrue("Removing an entry should succeed", list.remove(2) != null); + assertTrue("List should have 2 elements", list.size() == 2); } } diff --git a/src/test/java/org/json/junit/JSONObjectTest.java b/src/test/java/org/json/junit/JSONObjectTest.java index 73029e7..10405b0 100644 --- a/src/test/java/org/json/junit/JSONObjectTest.java +++ b/src/test/java/org/json/junit/JSONObjectTest.java @@ -2141,5 +2141,14 @@ public class JSONObjectTest { assertTrue("key3 list val 2 should not be null", key3Val2List != null); assertTrue("key3 list val 2 should have 1 element", key3Val2List.size() == 1); assertTrue("key3 list val 2 list element 1 should be null", key3Val2List.get(0) == null); + + // Assert that toMap() is a deep copy + jsonObject.getJSONArray("key3").getJSONArray(0).put(0, "still value 1"); + assertTrue("key3 list val 1 list element 1 should be value1", key3Val1List.get(0).equals("value1")); + + // assert that the new map is mutable + assertTrue("Removing a key should succeed", map.remove("key3") != null); + assertTrue("Map should have 2 elements", map.size() == 2); + } }