package it.univr.di.cstnu.util; import it.unimi.dsi.fastutil.objects.Object2ObjectMap; import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; import it.unimi.dsi.fastutil.objects.ObjectObjectImmutablePair; import it.univr.di.cstnu.graph.LabeledNode; import org.junit.Test; import static org.junit.Assert.*; /** * A simple JUnit 4 test to demonstrate the use of ObjectObjectImmutablePair as a key in a map. * It verifies that two different instances of the pair are treated as the same key * if they contain the same objects in the same order. */ public class MapKeyPairTest { /** * */ @Test public void testObjectObjectImmutablePairAsMapKey() { // 1. Dichiarazione della mappa final Object2ObjectMap, String> map = new Object2ObjectOpenHashMap<>(); // 2. Creazione dei nodi e del valore final LabeledNode nodeA = new LabeledNode("A"); final LabeledNode nodeB = new LabeledNode("B"); final LabeledNode nodeC = new LabeledNode("C"); final String expectedValue = "some data for A-B"; // 3. Creazione della chiave e inserimento nella mappa final ObjectObjectImmutablePair key1 = new ObjectObjectImmutablePair<>(nodeA, nodeB); map.put(key1, expectedValue); // 4. Creazione di una seconda chiave "uguale" per il recupero. // Due chiavi sono uguali se i nodi sono uguali e nello stesso ordine, // perché ObjectObjectImmutablePair implementa equals() e hashCode() correttamente. final ObjectObjectImmutablePair key2 = new ObjectObjectImmutablePair<>(nodeA, nodeB); // 5. Recupero del valore e asserzione final String retrievedValue = map.get(key2); assertEquals("The retrieved value should match the expected value.", expectedValue, retrievedValue); // 6. Verifica che la chiave originale e la seconda chiave siano considerate uguali assertEquals("The two keys should be equal.", key1, key2); assertEquals("The hash codes of the two keys should be equal.", key1.hashCode(), key2.hashCode()); // 7. Verifica che una chiave con ordine diverso non funzioni (se l'ordine è importante) final ObjectObjectImmutablePair reversedKey = new ObjectObjectImmutablePair<>(nodeB, nodeA); assertNull("A key with reversed nodes should not find the value.", map.get(reversedKey)); assertNotEquals("A key and its reverse should not be equal.", key1, reversedKey); // 8. Verifica che una chiave con nodi diversi non funzioni final ObjectObjectImmutablePair differentKey = new ObjectObjectImmutablePair<>(nodeA, nodeC); assertNull("A key with different nodes should not find the value.", map.get(differentKey)); } }