英文:
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<String,String> map) {
String desc = null;
for(Map.Entry<String,String> 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 = "item_1";
Map<String,String> map = new HashMap<String,String>();
map.put("item_1", "Description");
when(map.entrySet().contains(item)).thenReturn(true); //this doesn't work
String desc = lookup.getDesc(item, map);
assertEquals("Description", desc);
}
}
专注分享java语言的经验与见解,让所有开发者获益!
评论