@SuppressWarnings("unchecked") public void testSerializability() throws Exception { map.put("MORE", "STUFF"); checkMaps(true); ByteArrayOutputStream baos = new ByteArrayOutputStream(1024); ObjectOutputStream os = new ObjectOutputStream(baos); os.writeObject(map); os.close(); // Read it back in ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); ObjectInputStream ois = new ObjectInputStream(bais); ValueProtectingMap<String, Serializable> reloadedMap = (ValueProtectingMap<String, Serializable>) ois.readObject(); ois.close(); // Make sure it has the value assertEquals("Reloaded object not same.", "STUFF", reloadedMap.get("MORE")); } }
/** * Make sure that NOTHING has changed in our 'holy' map */ private void checkMaps(boolean expectMapClone) { assertEquals("Holy map size is wrong: ", 5, holyMap.size()); // Note that the immutability of the maps and lists means that we don't need // to check every value within the lists and maps if (expectMapClone) { // Make sure that the holy map has been released assertTrue("Expect holy map to have been released: ", map.getProtectedMap() != holyMap); // Do some updates to the backing map and ensure that they stick Map<String, Serializable> mapClone = map.getProtectedMap(); mapClone.put("ONE", "ONE"); assertEquals("Modified the backing directly but value is not visible: ", map.get("ONE"), "ONE"); map.put("TWO", "TWO"); assertTrue("Backing map was changed again!", mapClone == map.getProtectedMap()); mapClone.containsKey("TWO"); } else { // Make sure that the holy map is still acting as the backing map assertTrue("Expect holy map to still be in use: ", map.getProtectedMap() == holyMap); } }
/** * Ensures that single, immutable values are given out as-is and * without affecting the backing storage */ public void testMapGetImmutable() { assertTrue("Immutable value instance incorrect", map.get("IMMUTABLE") == valueImmutable); checkMaps(false); }
/** * Ensures that single, immutable values are cloned before being given out * without affecting the backing storage */ public void testMapGetMutable() { TestMutable mutable = (TestMutable) map.get("MUTABLE"); assertFalse("Mutable value instance incorrect", mutable == valueMutable); checkMaps(false); // Modify the instance mutable.increment(); assertEquals("Backing mutable should not have changed: ", 0, valueMutable.i); }