【问题标题】:Returning a new ArrayList, the list that is being returned is populated but still gives a null pointer exception返回一个新的 ArrayList,正在返回的列表被填充但仍然给出一个空指针异常
【发布时间】:2017-04-12 10:07:34
【问题描述】:

我正在为一个方法编写一个 JUnit 测试用例,该方法将我引导到另一个默认方法,当调用该默认方法时它返回一个新的 ArrayList。

测试方法

public List getTagDataForImage(String tagType, String imageType) {
        List tagRules = getTagRulesForUpdateOrQueryImage(tagType, imageType);
        List tagData = getTagData(tagRules);
        return tagData;
    }

在方法中,堆栈跟踪将我指向getTagRulesForUpdateOrQueryImage(tagType, imageType);,这将我引到这里

List getTagRulesForUpdateOrQueryImage(String tagType, String imageType) {
        List commonList = tagList.getTagRulesForUpdateOrQueryImage(tagType
                + "," + imageTypes[0]); //This line 
        commonList.addAll(tagList.getTagRulesForUpdateOrQueryImage(tagType
                + "," + imageType));
        return commonList;
    }

tagList.getTagRulesForUpdateOrQueryImage(tagType + "," + imageTypes[0]); 的定义在另一个类中定义

List getTagRulesForUpdateOrQueryImage(String tagType) {
        return new ArrayList((List) tagRulesMap.get(tagType));//gives NPE
    }

tagRulesMap 是一个在构造函数调用时自动填充的 HashMap

测试用例

@InjectMocks 
    TagDataFilter tagDataFilter;
    @Test
        public void testGetTagDataForImage()
        {
            List get=tagDataFilter.getTagDataForImage("QueryImages", "Common");
        }

堆栈跟踪

java.lang.NullPointerException
    at java.util.ArrayList.<init>(Unknown Source)
    at data.TagList.getTagRulesForUpdateOrQueryImage(TagList.java:107)
    at data.TagDataFilter.getTagRulesForUpdateOrQueryImage(TagDataFilter.java:92)
    at data.TagDataFilter.getTagDataForImage(TagDataFilter.java:73)
    at data.test.TagDataFilterTest.testGetTagDataForImage(TagDataFilterTest.java:54)

我无法弄清楚我哪里出错了。请帮我解决这个问题。

【问题讨论】:

  • 你的模拟 TagDataFilter 没有调用真正的构造函数吗?
  • 是的,它正在调用真正的构造函数
  • 如何模拟 tagList 依赖?
  • 我没有嘲笑它,因为我调用测试类的构造函数时会自动调用tagList的构造函数。
  • 它是否包含您正在搜索的键的值?如果未找到传递的键的值,则 ArrayList.get 返回 null...

标签: unit-testing junit nullpointerexception mockito powermockito


【解决方案1】:

只是为了提供来自 cmets 的答案:

List getTagRulesForUpdateOrQueryImage(String tagType) {
    return new ArrayList((List) tagRulesMap.get(tagType));//gives NPE
}

未找到键 tagType,因此它返回 null,然后尝试强制转换,然后返回 NullPointerException。

【讨论】:

    猜你喜欢
    • 2023-03-11
    • 1970-01-01
    • 1970-01-01
    • 2020-06-07
    • 1970-01-01
    • 1970-01-01
    • 2014-05-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多