[英]Null Pointer Exception on getObjectValue() using mockito
代码段
private AttributeCache attributeCache;
attributeCache = mock(AttributeCache.class);
ServiceAttribute serviceAttribute = new ServiceAttribute();
String serviceAttrId = "M";
when(attributeCache.get(serviceAttrId).getObjectValue()).thenReturn(serviceAttribute);
当方法由于getObjectValue()而引发Null指针异常时,当我删除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
类型为Attribute
; 您必须将其替换为实际的课程类型。
编辑:我试图重现您在更改的版本中获得的错误,但没有成功。 这是我的版本:
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()
可能会有所帮助,具体取决于问题所在。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.