小编Jef*_*f E的帖子

如何断言Map包含带有条目的Map

我有一个单元测试,需要检查嵌套的映射值.我可以通过拉出条目并匹配底层来让我的断言工作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")));
    }
}
Run Code Online (Sandbox Code Playgroud)

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

提前致谢.

java junit hamcrest

10
推荐指数
3
解决办法
2万
查看次数

标签 统计

hamcrest ×1

java ×1

junit ×1