imansdn
imansdn

Reputation: 1257

Why does `TextUtils.isDigitsOnly()` always return `false` in unit tests?

Issue with TextUtils.isDigitsOnly() in unit tests

I am trying to add a unit test for a function that uses TextUtils.isDigitsOnly(), but it always returns false for any input, like TextUtils.isDigitsOnly("111") or TextUtils.isDigitsOnly("aaa") always returns false.

I tried to rewrite the same function from the Android SDK in my test file, but that works. So, it might be something related to calling TextUtils.isDigitsOnly() in the test environment.

my android SDK version: 33

Question

Any idea on how to handle this issue in unit tests?

enter image description here

Upvotes: 1

Views: 167

Answers (3)

nvdk
nvdk

Reputation: 1

You can add RobolectricTestRunner to make it run within Android.

@RunWith(RobolectricTestRunner.class)
@Config(sdk = Config.NEWEST_SDK)
public class TestClass {
  // Tests
}

Upvotes: 0

imansdn
imansdn

Reputation: 1257

As @commonsware mentioned the reason is that we don't access SDK in Unit Test but JDK, So here is how I tried to resolve the issue by mocking TextUtils:

first I added this function in my test file:

  private fun String.isDigitsOnly(): Boolean {
        val len = this.length
        var i = 0
        while (i < len) {
            val cp = Character.codePointAt(this, i)
            if (!Character.isDigit(cp)) {
                return false
            }
            i += Character.charCount(cp)
        }
        return true
    }

then added this to @before function:

  @Before
    fun setUp() {
        mockkStatic(TextUtils::class)
        every { TextUtils.isDigitsOnly(any()) } answers { arg<String>(0).isDigitsOnly() }
    }

and then the test function should work like this:

 @Test
    fun `test isDigitsOnly from TextUtils`() {
           assert(TextUtils.isDigitsOnly("134344"))
    }

This approach allows us to mock the TextUtils.isDigitsOnly() method and provide a custom implementation for the test.

Upvotes: 2

CommonsWare
CommonsWare

Reputation: 1006574

TextUtils exists in the Android SDK, not the JDK. A unit test does not run on Android and so has no access to Android SDK classes. You are getting some sort of stub implementation in your unit test, and perhaps it is hard-coded to always return false.

Upvotes: 1

Related Questions