Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TextUtils.isEmpty() method returning false for an empty string

Tags:

android

I have below test which is returning false. Am I missing something?

TextUtils.isEmpty("")

Update: For some reason I am not able to answer to my question or add comment. I am running JUNit test case and not the instrumentation test case. As, suggested I found out that the above method returns incorrect value when we don't run as an Instrumentation. Thanks every one for help. I have upvoted the answer and correct comment.

like image 618
Akshay Avatar asked Jun 06 '16 18:06

Akshay


1 Answers

It should return true for empty string. From the source of TextUtils:

public static boolean isEmpty(@Nullable CharSequence str) {
    if (str == null || str.length() == 0)
        return true;
    else
        return false;
    }

In tests try using something like:

   mockStatic(TextUtils.class);

    when(TextUtils.isEmpty(any(CharSequence.class))).thenAnswer(new Answer<Boolean>() {
        @Override
        public Boolean answer(InvocationOnMock invocation) throws Throwable {
            Object[] args = invocation.getArguments();
            String string = (String) args[0];
            return (string == null || string.length() == 0);
        }
    });
like image 118
damjanh Avatar answered Nov 14 '22 23:11

damjanh