Reputation: 1257
TextUtils.isDigitsOnly()
in unit testsI 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
Any idea on how to handle this issue in unit tests?
Upvotes: 1
Views: 167
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
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
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