Skip to content
Advertisement

Wrong values from string empty test (java x kotlin)

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

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement