From 6cadb7c9024b0b9550a187b437eae1bf034a714f Mon Sep 17 00:00:00 2001 From: Mo Helmy <135069400+BenHelmyBen@users.noreply.github.com> Date: Mon, 4 Sep 2023 13:12:03 +0300 Subject: [PATCH] This commit related to the article BAEL-6877 (#14676) This commit aims to add a new test class to convert a HashMap string into a HashMap object using toString(). --- .../baeldung/map/UsingtoStringUnitTest.java | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 core-java-modules/core-java-collections-maps/src/test/java/com/baeldung/map/UsingtoStringUnitTest.java diff --git a/core-java-modules/core-java-collections-maps/src/test/java/com/baeldung/map/UsingtoStringUnitTest.java b/core-java-modules/core-java-collections-maps/src/test/java/com/baeldung/map/UsingtoStringUnitTest.java new file mode 100644 index 0000000000..4af6b72a4e --- /dev/null +++ b/core-java-modules/core-java-collections-maps/src/test/java/com/baeldung/map/UsingtoStringUnitTest.java @@ -0,0 +1,42 @@ +package com.baeldung.map; + +import org.junit.Test; + +import java.util.HashMap; + +import static org.junit.Assert.assertEquals; + +public class UsingtoStringUnitTest { + + @Test + public void given_HashMapString_whenUsingtoString_thenConvertToHashMapObject() { + // Example string representation of a HashMap + String hashMapString = "{key1=value1, key2=value2, key3=value3}"; + + // Remove unnecessary characters + String keyValuePairs = hashMapString.replaceAll("[{}\\s]", ""); + + // Split into individual key-value pairs + String[] pairs = keyValuePairs.split(","); + + // Create a new HashMap + HashMap expectedHashMap = new HashMap<>(); + expectedHashMap.put("key1", "value1"); + expectedHashMap.put("key2", "value2"); + expectedHashMap.put("key3", "value3"); + + HashMap actualHashMap = new HashMap<>(); + + // Parse and populate the HashMap + for (String pair : pairs) { + String[] keyValue = pair.split("="); + if (keyValue.length == 2) { + actualHashMap.put(keyValue[0], keyValue[1]); + } + } + + // Assert that the converted HashMap matches the expected one + assertEquals(expectedHashMap, actualHashMap); + } + +}