How do you test code that uses HashMap?

Testing code that utilizes HashMap in Java is essential to ensure the integrity and performance of the data structure. HashMap provides a way to store key-value pairs, allowing for efficient data retrieval. Below is a simple example of a HashMap implementation in Java, along with basic unit tests using JUnit.

import java.util.HashMap; import org.junit.Assert; import org.junit.Test; public class HashMapTest { @Test public void testHashMap() { HashMap map = new HashMap<>(); map.put("one", 1); map.put("two", 2); map.put("three", 3); // Test size Assert.assertEquals(3, map.size()); // Test containsKey Assert.assertTrue(map.containsKey("two")); // Test get Assert.assertEquals(Integer.valueOf(2), map.get("two")); } @Test public void testRemove() { HashMap map = new HashMap<>(); map.put("one", 1); map.put("two", 2); map.remove("one"); // Test removal Assert.assertFalse(map.containsKey("one")); Assert.assertEquals(1, map.size()); } }

HashMap Java JUnit Unit Testing Data Structures Performance Testing