Android Espresso:检查TextView是否显示资源中的格式化字符串

时间:2020-01-23 08:08:11

标签: android android-espresso android-resources

假设您有一个格式化字符串,如下所示:

<string name="saving">You saved %1$s with %2$s</string>

现在,如果您想检查TextView是否正确显示,那么自然可以进行以下操作:

 Espresso.onView(withId(R.id.tv))
            .check(matches(withText(R.string.saving)))

但是它不能,我不能检查带有硬编码字符串的文本,因为它可能是另一种语言。那么有没有办法呢?

1 个答案:

答案 0 :(得分:0)

也许是这样的:

Espresso.onView(withId(R.id.tv))
        .perform(object :ViewAction{
            override fun getDescription(): String {
                return "Normalizing the string"
            }

            override fun getConstraints(): Matcher<View> {
                return isAssignableFrom(TextView::class.java)
            }

            override fun perform(uiController: UiController?, view: View?) {
                val tv = view as TextView
                if (tv.text.matches(Regex("You saved (.)*? with (.)*"))) {
                    tv.text = "You saved %1\$s with %2\$s"
                }
            }
        }).check(matches(withText(R.string.saving)))
相关问题