From 9e21e95e6fc6dbf8ce6503b23a7324fa750bc2ef Mon Sep 17 00:00:00 2001 From: Muhammad Asif Date: Wed, 27 Mar 2024 21:57:34 +0500 Subject: [PATCH] BAEL-7030 Added the example code (#16085) * BAEL-7030 Added the example code * Removed public modifier --- .../ImmutableCollectionsUnitTest.java | 54 +++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 core-java-modules/core-java-collections-5/src/test/java/com/baeldung/immutables/ImmutableCollectionsUnitTest.java diff --git a/core-java-modules/core-java-collections-5/src/test/java/com/baeldung/immutables/ImmutableCollectionsUnitTest.java b/core-java-modules/core-java-collections-5/src/test/java/com/baeldung/immutables/ImmutableCollectionsUnitTest.java new file mode 100644 index 0000000000..6daec6d959 --- /dev/null +++ b/core-java-modules/core-java-collections-5/src/test/java/com/baeldung/immutables/ImmutableCollectionsUnitTest.java @@ -0,0 +1,54 @@ +package com.baeldung.immutables; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +import org.junit.jupiter.api.Test; + +class ImmutableCollectionsUnitTest { + + @Test + void givenUnmodifiableMap_whenPutNewEntry_thenThrowsUnsupportedOperationException() { + Map modifiableMap = new HashMap<>(); + modifiableMap.put("name1", "Michael"); + modifiableMap.put("name2", "Harry"); + + Map unmodifiableMap = Collections.unmodifiableMap(modifiableMap); + + assertThrows(UnsupportedOperationException.class, () -> unmodifiableMap.put("name3", "Micky")); + } + + @Test + void givenUnmodifiableMap_whenPutNewEntryUsingOriginalReference_thenSuccess() { + Map modifiableMap = new HashMap<>(); + modifiableMap.put("name1", "Michael"); + modifiableMap.put("name2", "Harry"); + + Map unmodifiableMap = Collections.unmodifiableMap(modifiableMap); + modifiableMap.put("name3", "Micky"); + + assertEquals(modifiableMap, unmodifiableMap); + assertTrue(unmodifiableMap.containsKey("name3")); + } + + @Test + void givenImmutableMap_whenPutNewEntry_thenThrowsUnsupportedOperationException() { + Map immutableMap = Map.of("name1", "Michael", "name2", "Harry"); + + assertThrows(UnsupportedOperationException.class, () -> immutableMap.put("name3", "Micky")); + } + + @Test + void givenImmutableMap_whenUsecopyOf_thenExceptionOnPut() { + Map immutableMap = Map.of("name1", "Michael", "name2", "Harry"); + Map copyOfImmutableMap = Map.copyOf(immutableMap); + + assertThrows(UnsupportedOperationException.class, () -> copyOfImmutableMap.put("name3", "Micky")); + } +} +