0

I created a validation use case in which I'm validating the input using isDigitsOnly that use TextUtils internally.

override fun isDigitsOnly(size: String): Boolean {
    return !size.trim().isDigitsOnly()
}

when I tried to test it, I got this error

Method isDigitsOnly in android.text.TextUtils not mocked

Does anyone know how I can mock the textUtils in my test class

@RunWith(MockitoJUnitRunner::class)
class ValidationInputImplTest {

    @Mock
    private lateinit var mMockTextUtils: TextUtils

    private lateinit var validationInputImpl: ValidationInputImpl

    @Before
    fun setUp() {
        validationInputImpl = ValidationInputImpl()
    }

    @Test
    fun `contains only digits, returns success`() {
        val input = "66"
        val result = validationInputImpl(input)
        assertTrue(result is ValidationResult.Success)
    }

}
Omar Redani
  • 131
  • 5
  • 1
    Check out this answer from a previous question https://stackoverflow.com/a/50911921/17118761. – hayzie101 Jan 13 '23 at 17:08
  • Thank you, but I'm still looking for a better solution. – Omar Redani Jan 13 '23 at 17:42
  • Why do you have to mock the `isDigitsOnly` method? It seems simple enough to just use the real implementation? – knittl Jan 15 '23 at 08:13
  • I found a better solution by not using TextUtils completely and use an extension function to replace isDigitsOnly `fun String.isDigitsOnly() = all(Char::isDigit) && isNotEmpty()` – Omar Redani Jan 15 '23 at 14:54

1 Answers1

0

At the time of writing the answer,you cannot do that. Because the android code ,that you see is not actual code. You cannot create unit test for that. The default implementation of the methods in android.jar is to throw exception.

One thing you can do is, adding the below in build.gradle file. But it make the android classes not to throw exception. But it will always return default value. So the test result may actually not work. It is strictly not recommended.

android {
  testOptions { 
    unitTests.returnDefaultValues = true
  }
}

The better way to do copy the code from android source and paste the file under src/test/java folder with package name as android.text .

Link to Answer

Gowtham K K
  • 3,123
  • 1
  • 11
  • 29