Mokito单元测试覆盖Map.Entry

huangapple 未分类评论56阅读模式
英文:

Mokito unit test over Map.Entry

问题

我已经到处搜索但找不到答案

请帮帮忙将不胜感激

以下是我的类

    @Component
    public class Lookup {
    
        protected String getDesc(String item, Map<String,String> map) {
            String desc = null;
            for(Map.Entry<String,String> entry: map.entrySet()){
                if(entry.getKey().equalsIgnoreCase(item)) {
                    desc = entry.getValue();
                }
            }
            return desc;
        }
    }

以下是我的测试类
如果我去掉对 EntrySet 的检查代码能够运行但不能覆盖 if 语句

    @RunWith(MockitoJUnitRunner.class)
    public class LookupTest {

        @InjectMocks Lookup lookup;
    
        @Test
        public void testLookup_Item() {

            String item = "item_1";
            Map<String,String> map = new HashMap<String,String>();
            map.put("item_1", "Description");
        
            when(map.entrySet().contains(item)).thenReturn(true);  // 这段代码不起作用
        
            String desc = lookup.getDesc(item, map);
            assertEquals("Description", desc);
        }
    }
英文:

I have searched everywhere but couldn't find the answer.

Please any help would be greatly appreciated.

Here is my class

@Component
public class Lookup {

    protected String getDesc(String item, Map&lt;String,String&gt; map) {
	    String desc = null;
	    for(Map.Entry&lt;String,String&gt; entry: map.entrySet()){
		    if(entry.getKey().equalsIgnoreCase(item) {
			    desc = entry.getValue();
		    }
	    }
	    return desc;
    }
}

Here is my test class
If I remove the check on EntrySet, it works but doesn't covered the if statement

@RunWith(MockitoJUnitRunner.class)
public class LookupTest {

    @InjectMocks Lookup lookup;

    @Test
    public void testLookup_Item() {

	    String item = &quot;item_1&quot;;
	    Map&lt;String,String&gt; map = new HashMap&lt;String,String&gt;();
	    map.put(&quot;item_1&quot;, &quot;Description&quot;);
	
	    when(map.entrySet().contains(item)).thenReturn(true);  //this doesn&#39;t work
	
	    String desc = lookup.getDesc(item, map);
	    assertEquals(&quot;Description&quot;, desc);
    }
}

huangapple
  • 本文由 发表于 2020年7月29日 00:07:14
  • 转载请务必保留本文链接:https://java.coder-hub.com/63138351.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定