0

I'm having a super weird behavior from a code that I was testing. The test I wrote was to see the behavior of the class if the Android returned an empty package name. After some debugging, I found this (consider that packageName is empty):

 val resultFromKotlin = packageName.isNullOrEmpty()
 val resultFromJava = StringUtils.isEmpty(packageName)

Image from Andriod Studio debug

Is this expected? Can someone tell what the deal with this?

ps1.: In the picture above, Android Studio was complaining of isNullOrEmpty saying that could be simplified since packageName can't be null at that point.

ps2.: For references:

The StringUtils class is written in Java as follow:

public static boolean isEmpty(String str) {
    return str == null || TextUtils.isEmpty(str.trim());
}

TextUtils is also from Java, but it's part of Android library:

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

This is how kotlin implements it's extension method:

public inline fun CharSequence?.isNullOrEmpty(): Boolean {
    contract {
        returns(false) implies (this@isNullOrEmpty != null)
    }

    return this == null || this.length == 0
}

EDIT 08/11/2018: Just for clarification, my problem is the wrong value returned from Java, not searching for an equivalence in the test, also: enter image description here

1 Answer 1

2

This seems to be a problem with TextUtils when running tests.

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.

Here is where the issue is discussed.

I have tested manually by recreating the function, and it is returning true.

I would suggest using Apache Commons StringUtils implementation: StringUtils

Sign up to request clarification or add additional context in comments.

1 Comment

Humm.. that's explains a lot.. thanks for this answer.

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.