代码片段
private AttributeCache attributeCache;
attributeCache = mock(AttributeCache.class);
ServiceAttribute serviceAttribute = new ServiceAttribute();
String serviceAttrId = "M";
when(attributeCache.get(serviceAttrId).getObjectValue()).thenReturn(serviceAttribute);
当方法由于 getObjectValue() 抛出空指针异常时,当我删除 getObjectValue 时,它给出了一个错误,将 serviceAttribute 的类型更改为 Element?
任何更新!对于上述场景我们如何使用mockito?
在正常情况下,我们按如下方式转换对象
serviceAttribute = (ServiceAttribute) (attributeCache.get(serviceAttrId).getObjectValue());
最佳答案
这里的问题是在尝试模拟时调用attributeCache.get(serviceAttrId).getObjectValue()
; attributeCache.get(serviceAttrId)
部分将返回 null
,这会给您带来 NullPointerException
。解决方案如下:
private AttributeCache attributeCache;
attributeCache = mock(AttributeCache.class);
ServiceAttribute serviceAttribute = new ServiceAttribute();
Attribute attribute = mock(Attribute.class);
when(attributeCache.get(Matchers.any(String.class)).thenReturn(attribute);
String serviceAttrId = "M";
when(attribute.getObjectValue()).thenReturn(serviceAttribute);
这是假设 attributeCache.get(...)
返回 Attribute
类型的内容;您必须将其替换为实际的类(class)类型。
编辑:我尝试重现您在更改版本中遇到的错误,但没有成功。这是我的版本:
package com.stackoverflow.shahid.ghafoor;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class MockStuff {
public static void main(String[] args) {
try {
new MockStuff().run();
System.out.println("Everything's fine");
} catch(Exception e) {
System.err.println("Caught an error:");
e.printStackTrace();
}
}
public MockStuff() {
}
public void run() {
AttributeCache attributeCache;
attributeCache = mock(AttributeCache.class);
ServiceAttribute serviceAttribute = new ServiceAttribute();
Attribute attribute = mock(Attribute.class);
when(attributeCache.get(any(String.class))).thenReturn(attribute);
String serviceAttrId = "M";
when(attribute.getObjectValue()).thenReturn(serviceAttribute);
}
private class AttributeCache {
Attribute get(String something) {
return null;
}
}
private class Attribute {
ServiceAttribute getObjectValue() {
return null;
}
}
private class ServiceAttribute {
}
}
当然有可能您在这里遇到了 Mockito 的限制;如果是这样切换
Mockito.when(attribute.getObjectValue()).thenReturn(serviceAttribute)
至
Mockito.doReturn(serviceAttribute).when(attribute).getObjectValue()
可能会有所帮助,具体取决于问题到底是什么。
关于java - 使用mockito在getObjectValue()上出现空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25791703/