8

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.

6
  • 1
    Are sure you're using Andoid textutils? Are you running it in unit tests? Commented Jun 6, 2016 at 18:38
  • 2
    Are you sure that? Commented Jun 6, 2016 at 18:39
  • 1
    and cross verify looking at the source code grepcode.com/file/repository.grepcode.com/java/ext/… Commented Jun 6, 2016 at 18:40
  • 14
    If you are running unit tests, Android frameworks methods are mocked, and this one in particular returns false. Use instrumentation tests to run against a full Android runtime. Commented Jun 6, 2016 at 19:03
  • @njzk2 Thanks, yes this was exactly the issue! Commented Jun 15, 2016 at 17:10

2 Answers 2

4

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);
        }
    });
Sign up to request clarification or add additional context in comments.

4 Comments

Check @njzk2 comment above (should be an answer), OP is really getting false because the method is mocked.
See the comment dates. The additional info was not provided at the time of the answer.
Right, it's not a correction to your answer, but info for readers that get here, it's one of the first matches in google for that problem.
OP here... Yes, I wasn't aware at the time of posting that the issue was because I was running JUnit test case. Although, I haven't accepted this answer, I have given thumbs up to @damjanh!
2

If you are using Kotlin use isNullOrBlank() or isNullOrEmpty() methods instead. You don't need any mocking for tests.

3 Comments

This question was for Java, but thanks for your answer.
In the tags, I only see 'android'. Anyway, everyone should switch to Kotlin now.
True, but notice that the question was asked in 2016, when Google didn't officially support Kotlin.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.