使用mockito在getObjectValue()上的空指针异常

时间:2014-09-11 15:39:42

标签: java mockito

代码段

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());

1 个答案:

答案 0 :(得分:2)

这里的问题是在你试图模仿时调用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类型的内容;你必须用实际的课程类型来代替它。


编辑:我尝试重现您在更改后的版本中获得的错误,但没有成功。这是我的版本:

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()

可能有所帮助,具体取决于问题究竟是什么。

相关问题