You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android测试中DesignInputField的checkTextLength()始终返回false如何解决

问题根因与解决方法

核心错误点

  • 你对被测类DesignInputField本身使用了Mockito Mock:Mock对象的所有未手动打桩的方法都会返回对应类型的默认值,布尔类型默认返回false,这就是你无论怎么设置text的打桩值,checkTextLength()都返回false的原因。你直接Mock了整个被测类,等于完全没测真实的业务逻辑,直接打桩checkTextLength()返回true的做法更是没有任何测试意义。
  • 你贴出的DesignInputField代码存在语法结构错误:checkTextLength()方法定义在了类的大括号外部,无法访问类内部的私有属性textLength、textLengthType,请先将方法移入类内部,同时补充你类内部text属性的定义(通常是内部持有EditText实例,取其输入内容)。

正确测试方案

自定义View的单元测试推荐使用Robolectric框架提供模拟Android Context,不需要Mock整个被测类,直接构造真实实例测试即可:

第一步:引入Robolectric依赖(如果未引入)

在模块级build.gradle.kts的testImplementation中添加依赖:

testImplementation("junit:junit:4.13.2")
testImplementation("org.robolectric:robolectric:4.12.1")
testImplementation("org.mockito:mockito-core:5.6.0")

第二步:调整测试代码

@RunWith(RobolectricTestRunner::class)
class DesignInputFieldTest {
    // 构造真实的被测实例,不要Mock
    private lateinit var designInputField: DesignInputField

    @Before
    fun setUp() {
        // 使用Robolectric提供的模拟Context构造实例
        designInputField = DesignInputField(ApplicationProvider.getApplicationContext())
        // 如果textLength、textLengthType是私有属性,要么添加公开setter方法,要么用反射修改测试值
        // 示例用反射修改私有属性,也可以在自定义View中添加测试友好的setter
        val textLengthField = DesignInputField::class.java.getDeclaredField("textLength")
        textLengthField.isAccessible = true
        textLengthField.setInt(designInputField, 1)

        val textLengthTypeField = DesignInputField::class.java.getDeclaredField("textLengthType")
        textLengthTypeField.isAccessible = true
        textLengthTypeField.setInt(designInputField, 1)
    }

    @Test
    fun `cardNameGreaterThanOne返回true`() {
        // 设置输入文本为"ab",长度为2>1,符合textLengthType=1的判定规则
        // 假设你内部text属性是EditText的内容,直接设置EditText的文本即可
        val editText = designInputField.findViewById<EditText>(R.id.your_edittext_id)
        editText.setText("ab")
        // 调用真实的方法断言
        Assert.assertEquals(true, designInputField.checkTextLength())
    }
}

可选简化方案

如果不想用反射修改私有属性,可以在DesignInputField中添加公开配置方法,用于测试和业务调用:

fun setLengthCheckRule(textLength: Int, @IntRange(from = 0, to = 4) type: Int) {
    this.textLength = textLength
    this.textLengthType = type
}

测试时直接调用该方法设置规则即可,无需反射。


内容的提问来源于stack exchange,提问作者Ahmet Yilmaz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 20:24:06