Search code examples
androidkotlinjunitmockitopowermockrunner

java.lang.NullPointerException for null input in null safe static method


@Test
fun isEmpty_null_true(){
    Assert.assertEquals(StringUtils.isEmpty(null),true)
}

public static boolean isEmpty(@Nullable String value) {
    return (TextUtils.isEmpty(value) || value.trim().isEmpty());
}

All test methods except above one are working and passed. I am getting java.lang.NullPointerException for this one. The implementation of StringUtils.isEmpty() is also mentioned above. StringUtils class is written in Java whereas test case file is written in Kotlin.


Solution

  • The complete solution, I have got-
    Due to default values set in app/build.gradle, I was getting false returned from TextUtils.isEmpty() which was not expected by me.

    testOptions {
        unitTests.returnDefaultValues = true
    }
    

    Reference - TextUtils.isEmpty(null) returns false
    I cannot change the value in build.gradle file, so I needed the solution for my unit test method only. There is a way to provide implementation to TextUtils.isEmpty() method and get the real returned value.

        @Before
        public void setup() {
            PowerMockito.mockStatic(TextUtils.class);
            PowerMockito.when(TextUtils.isEmpty(any(CharSequence.class))).thenAnswer(new Answer<Boolean>() {
                @Override
                public Boolean answer(InvocationOnMock invocation) throws Throwable {
                    CharSequence a = (CharSequence) invocation.getArguments()[0];
                    return !(a != null && a.length() > 0);
                }
            });
       }
    

    Reference - Need help to write a unit test using Mockito and JUnit4

    I got the same problem with android.graphics.Color.parseColor() so above solution applies to all classes lies in android package.