如何断言地图包含带条目的地图

2022-09-04 03:01:36

我有一个单元测试,需要检查嵌套的映射值。我可以通过拉出条目并匹配基础来使我的断言起作用,但我正在寻找一种清晰的方式来显示断言在做什么。这是一个非常简化的测试:Map

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")));
    }
}

似乎问题是正在比较外部地图,而我想使用的是 。我不知道如何强制断言使用第二种形式。hasEntry(K key, V value)hasEntry(Matcher<? super K> keyMatcher, Matcher<? super V> valueMatcher)

提前致谢。


答案 1

如果您只想在声明中作为值进行相应的调整。然后你可以做Map<String, Object>outerMap

@Test
public void testMapHasMap() {
    Map<String, Map<String, Object>> outerMap = new HashMap<>();
    Map<String, Object> nestedMap = new HashMap<String, Object>();
    nestedMap.put("foo", "bar");
    outerMap.put("nested", nestedMap);

    Object value = "bar";
    assertThat(outerMap, hasEntry(equalTo("nested"), hasEntry("foo", value)));  
}

Object value = "bar";出于编译原因,这是必需的。或者,您可以使用

assertThat(outerMap,
   hasEntry(equalTo("nested"), Matchers.<String, Object> hasEntry("foo", "bar")));

答案 2

如果你声明outerMap,因为你不需要丑陋的演员。喜欢这个:Map<String, Map<String, Object>>

public class MapContainsMapTest {

    @Test
    public void testMapHasMap() {
        Map<String, Map<String, Object>> outerMap = new HashMap<>();
        Map<String, Object> nestedMap = new HashMap<>();
        nestedMap.put("foo", "bar");
        outerMap.put("nested", nestedMap);

        assertThat(outerMap.get("nested"), hasEntry("foo", "bar"));
    }
}

推荐