Ho un test di unità che deve controllare un valore di mappa annidato. Posso far funzionare la mia affermazione estraendo la voce e facendo corrispondere il sottostante Map
, ma stavo cercando un modo chiaro per mostrare cosa sta facendo l'affermazione. Ecco un test molto semplificato:Come affermare Mappa contiene Mappa con voce
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasEntry;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
public class MapContainsMapTest {
@Test
public void testMapHasMap() {
Map<String, Object> outerMap = new HashMap<String, Object>();
Map<String, Object> nestedMap = new HashMap<String, Object>();
nestedMap.put("foo", "bar");
outerMap.put("nested", nestedMap);
// works but murky
assertThat((Map<String, Object>) outerMap.get("nested"), hasEntry("foo", "bar"));
// fails but clear
assertThat(outerMap, hasEntry("nested", hasEntry("foo", "bar")));
}
}
sembra che il problema è la mappa esterna viene confrontato con hasEntry(K key, V value)
mentre ciò che voglio usare è hasEntry(Matcher<? super K> keyMatcher, Matcher<? super V> valueMatcher)
. Non sono sicuro di come forzare l'asserzione per usare il secondo modulo.
Grazie in anticipo.
"_It sembra che il problema è la mappa esterna viene confrontato con ..._" 'hasEntry (è ("chiave"), è ("valore"))' per esempio potrebbe causare il secondo modulo da utilizzare. Forse potresti usare il matcher 'equalTo' al posto di' is', ma in entrambi i casi, la leggibilità esce dalla finestra. – mystarrocks
Il problema è con il test esterno, quindi ho bisogno di qualcosa come 'equalTo (" nested ") ...' ma ciò non funziona a meno che non cambi il tipo di mappa esterna in 'Map > ' –