[英]Mockito, JUnit and Map nested in another class
I'm beginner with Mockito and I have problem with creating stub. 我是Mockito的初学者,创建存根时遇到问题。 I have the following interface: 我有以下界面:
public interface IMsgField {
public String getName();
public Object getValue();
}
One class implements above interface as follows 一类如下实现上述接口
public final class CMsgField implements IMsgField {
private String name;
private Object value;
public CMsgField(String name, Object value) {
this.name = name;
this.value = value;
}
. . .
}
And I have one more class : 我还有一堂课:
class FieldsWrapper {
private Map<String, IMsgField> fields = new HashMap<String, IMsgField>();
. . .
public Map<String, IMsgField> getFields() {
return fields;
}
}
I've created the following junit test: 我创建了以下junit测试:
@Test
public void test() {
FieldsWrapper fieldsWrapper = mock(FieldsWrapper.class);
stub(fieldsWrapper.getFields()).toReturn(new HashMap<String, IMsgField>());
stub(fieldsWrapper.getFields().get("id_object")).toReturn(new CMsgField("id_object", "100"));
. . .
}
And when I ran this test I received the following exception at last line in above test : 当我运行此测试时,我在上述测试的最后一行收到以下异常:
org.mockito.exceptions.misusing.WrongTypeOfReturnValue:
CMsgField cannot be returned by getFields()
getFields() should return Map
...
I don't why, please help me with this problem. 我不为什么,请帮助我解决这个问题。 Thanks in advance. 提前致谢。
I would either mock the Map or use a local variable for it : 我可以模拟Map或对其使用局部变量:
@Test
public void test() {
Map<String, IMsgField> testMap = new HashMap<String, IMsgField>();
testMap.put("id_object", new CMsgField("id_object", "100"));
FieldsWrapper fieldsWrapper = mock(FieldsWrapper.class);
stub(fieldsWrapper.getFields()).toReturn(testMap);
}
You should rather proceed this way: 您应该这样做:
@Test
public void test() {
Map<String, IMsgField> stubbedMap = new HashMap<String, IMsgField>();
stubbedMap.put("id_object", new CMsgField("id_object", "100"));
FieldsWrapper fieldsWrapper = mock(FieldsWrapper.class);
stub(fieldsWrapper.getFields()).toReturn(stubbedMap);
}
Because you only have to stub fieldsWrapper.getFields(). 因为只需要对fieldsWrapper.getFields()进行存根。 testMap.get("id_object") is a method call from Map, which is not stubbed, so it can't work. testMap.get(“ id_object”)是Map中的一个方法调用,没有存根,因此无法正常工作。
You can not do chains of method calls while mocking. 模拟时不能进行方法调用链。
@Test
public void test() {
FieldsWrapper fieldsWrapper = mock(FieldsWrapper.class);
HashMap<String, IMsgField>() map = new HashMap<String, IMsgField>();
map.put("id_object", CMsgField("id_object", "100"));
stub(fieldsWrapper.getFields()).toReturn(map);
. . .
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.