Home > database >  Android test boolean method returns false every time?
Android test boolean method returns false every time?

Time:11-21

I want to test method checkTextLength() of DesignInputField that returns boolean value. But it returns false every time. Tried mock library to do this. When I write this code Mockito.when(designInputField.checkTextLength()).thenReturn(true) it returns true. But I think it's not right way to test this code.

DesignInputField.kt

 class DesignInputField @JvmOverloads constructor(
        context: Context,
        attrs: AttributeSet? = null,
        defStyleAttr: Int = 0
    ) : ConstraintLayout(context, attrs, defStyleAttr) {
        private var textLength = 1;
        private var textLengthType = 1;
        }
    
      fun checkTextLength(): Boolean {
            return when (textLengthType) {
                0 -> text.length < textLength
                1 -> text.length > textLength
                2 -> text.length <= textLength
                3 -> text.length >= textLength
                4 -> text.length == textLength
                else -> false
            }
        }

DesignInputFieldTest.kt

@RunWith(MockitoJUnitRunner::class)
class DesignInputFieldTest{
    @Mock
    lateinit var designInputField: DesignInputField
  @Test
    fun `cardNameGreaterThanOne`() {
        Mockito.`when`(designInputField.text).thenReturn("ab")
        Assert.assertEquals(true,designInputField.checkTextLength())
}

CodePudding user response:

The issue is that you're mocking designInputField, so all its functions are mocked, including checkTextLength.

You could resort to instrumented tests, but, in your case, I would suggest extracting the logic for checkTextLength into a helper top-level function and test that. E.g.:

fun checkTextLength(type: Int, text: String): Boolean {
    return when (type) {
        0 -> text.length < textLength
        1 -> text.length > textLength
        2 -> text.length <= textLength
        3 -> text.length >= textLength
        4 -> text.length == textLength
        else -> false
    }
}

Then, in DesignInputField you can call it:

fun checkTextLength() = checkTextLength(textLengthType, text)
  • Related