【问题标题】:Android test boolean method returns false every time?Android测试布尔方法每次都返回false?
【发布时间】:2021-11-20 06:55:24
【问题描述】:

我想测试返回布尔值的DesignInputField 的方法checkTextLength()。但它每次都返回false。尝试模拟库来做到这一点。当我写这段代码Mockito.when(designInputField.checkTextLength()).thenReturn(true) 它返回true。但我认为这不是测试这段代码的正确方法。

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())
}

【问题讨论】:

    标签: android kotlin testing mocking mockito


    【解决方案1】:

    问题是你在模拟designInputField,所以它的所有功能都被模拟了,包括checkTextLength。

    您可以求助于仪器测试,但在您的情况下,我建议将checkTextLength 的逻辑提取到辅助顶级函数中并对其进行测试。例如:

    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
        }
    }
    

    那么,你可以在DesignInputField中调用它:

    fun checkTextLength() = checkTextLength(textLengthType, text)
    

    【讨论】:

    • 非常感谢。我明白为什么我每次都弄错了。就我而言,我正在为我工​​作的公司现有项目编写这些测试。所以,我现在不会像你说的那样用 Helper 改变。如果您可以添加仪器测试代码,例如我们如何调用DesignInputField 类以及如何测试此方法,那就太好了。:)
    • 您可以尝试使用spy 而不是模拟。使用 spy,您只能模拟您想要模拟的功能。但是,您需要能够实例化 DesignInputField 才能对其进行监视。
    猜你喜欢
    • 2016-08-16
    • 2015-01-22
    • 2015-08-10
    • 1970-01-01
    • 2015-08-21
    • 1970-01-01
    • 2017-08-26
    • 1970-01-01
    • 2022-12-14
    相关资源
    最近更新 更多