Java Mockito只能模拟非私有和非最终类
在我的代码中,我有一个使用ObjectMapper.readValue的方法,为了测试的目的,我想模拟它。 下面是代码的分区:Java Mockito只能模拟非私有和非最终类,java,mockito,Java,Mockito,在我的代码中,我有一个使用ObjectMapper.readValue的方法,为了测试的目的,我想模拟它。 下面是代码的分区: if (entity != null) { String result = EntityUtils.toString(entity); ObjectMapper objectMapper = new ObjectMapper(); objec
if (entity != null) {
String result = EntityUtils.toString(entity);
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(JsonParser.Feature.AUTO_CLOSE_SOURCE, true);
return objectMapper.readValue(result, classeObjetRetour);
}
当我在我的测试课上尝试反编译时:
String retour = EntityUtils.toString(httpEntity);
IdentifiantEnveloppe identifiantAttendu = new IdentifiantEnveloppe();
ObjectMapper objectMapper = mock(ObjectMapper.class);
doReturn(identifiantAttendu).when(objectMapper).readValue(retour, IdentifiantEnveloppe.class);
我有以下错误:
org.mockito.exceptions.base.MockitoException:
Mockito cannot mock this class: class com.fasterxml.jackson.databind.ObjectMapper.
Mockito can only mock non-private & non-final classes.
If you're not sure why you're getting this error, please report to the mailing list.
如果有人能帮助我,我将不胜感激。我在Java 8
多谢各位
if (entity != null) {
String result = EntityUtils.toString(entity);
ObjectMapper objectMapper = new ObjectMapper(); // this line is the problem.
objectMapper.configure(JsonParser.Feature.AUTO_CLOSE_SOURCE, true);
return objectMapper.readValue(result, classeObjetRetour);
}
因为在上面创建了ObjectMapper的新实例,所以模拟无法工作。正如在测试课的最后一行中所说,永远不会发生:
String retour = EntityUtils.toString(httpEntity);
IdentifiantEnveloppe identifiantAttendu = new IdentifiantEnveloppe();
ObjectMapper objectMapper = mock(ObjectMapper.class);
doReturn(identifiantAttendu).when(objectMapper).readValue(retour, IdentifiantEnveloppe.class);
因为在启用时调用Mockito.when的objectMapper是类中的另一个实例。因此,永远不会在模拟上调用objectMapper.readValue
您应该尝试在类中模拟objectMapper。您可以将objectMapper定义为类字段,以便可以通过构造函数将objectMapper注入类中。然后,您可以在测试类中注入mockObjectMapper.class,而不是真正的类。ObjectMapper不应该是最终的或私有的。您使用的是哪个版本的Jackson databind?您好,我使用2.10.2版本的Jackson databind。我不认为您应该模拟ObjectMapper,它似乎不是一个注入的助手。ObjectMapper正在为您做一些工作。就我个人而言,我会编写测试,以便ObjectMapper接收有效和无效的输入,并测试您的类/方法在给定输入下的行为;我有一个错误:java.lang.NoClassDefFoundError:com/fasterxml/jackson/annotation/JsonMerge。