Search code examples
unit-testingjunitnullpointerexceptionmockitopowermockito

Returning a new ArrayList, the list that is being returned is populated but still gives a null pointer exception


I am writing a JUnit test case for a method that leads me to another method that is default, it returns a new ArrayList when that default method is called.

Test method

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

In the method the stack trace points me to getTagRulesForUpdateOrQueryImage(tagType, imageType); which leads me here

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

definition for tagList.getTagRulesForUpdateOrQueryImage(tagType + "," + imageTypes[0]); defined in another class

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

tagRulesMap is a HashMap that is populated automatically at constructor call

Test case

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

Stack Trace

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)

I am not able to figure out where I have gone wrong.Please help me solve this problem.


Solution

  • Just to provide a answer from the comments:

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

    the key tagType is not found and because of this it returns null which is then tried to cast which then returns a NullPointerException.