0

我已经像这样以编程方式设置了 GradientDrawable 背景,并试图测试它的颜色。主要问题似乎是在测试时从形状(GradientDrawable)中获取颜色。

这个片段来自一个更大的绑定适配器。

color = ContextCompat.getColor(
    textView.context, R.color.ColorRatingHigh
)

val shape = GradientDrawable()
shape.shape = GradientDrawable.OVAL
shape.setColor(color)
shape.setStroke(2, Color.BLACK)
textView.setBackground(shape)

测试是这样设置的..

@Test
fun MovieDetailRatingColorTest() {
    ...

    onView(withId(R.id.movie_vote_average))
        .check(matches(withBackgroundColor(R.color.ColorRatingHigh)))
}
...

fun withBackgroundColor(expectedColor: Int): Matcher<View?>? {
    Checks.checkNotNull(expectedColor)
    return object : BoundedMatcher<View?, TextView>(TextView::class.java) {
        override fun matchesSafely(textView: TextView): Boolean {

            val actualColor = (textView.getBackground() as ColorDrawable).color
            return expectedColor == actualColor
        }

        override fun describeTo(description: Description) {
            description.appendText("with background color: ")
        }
    }
}

不幸的是,我收到以下 ClassCastException

android.graphics.drawable.GradientDrawable cannot be cast to android.graphics.drawable.ColorDrawable

我在网站上看到了一些关于类似问题的帖子,

但似乎都没有工作,而且大多数最终都遇到了同样的问题。例如,测试背景色浓缩咖啡 Android

或者有看起来过时的答案或从 java 到 kotlin 转换的问题.. 例如如何从 GradientDrawable 获取颜色

4

1 回答 1

1

想出了一个解决方法,使用片段场景来访问“ContextCompat”。

这使我能够检索“R.color”目录。getColor 检索最初传入的 colorId 的 2 的补码...恰好与此处检索的 id 匹配: val actualColor = (textView.getBackground() as ColorDrawable).color.defaultColor

lateinit var scenario: FragmentScenario<MovieDetailFragment>
...

@Test
fun MovieDetailRatingColorTest() {
    var expectedColor: Int? = 0

    scenario.onFragment { fragment ->
            expectedColor =
                fragment.context?.let {
                    ContextCompat.getColor(it, R.color.ColorRatingHigh )
                }
    }

    onView(withId(R.id.movie_vote_average))
        .check(matches(withBackgroundColor(expectedColor)))
}

然后我编辑了 withBackground() 函数以匹配新输入

fun withBackgroundColor(expectedColor: Int?): Matcher<View?>? {
    Checks.checkNotNull(expectedColor)
    return object : BoundedMatcher<View?, TextView>(TextView::class.java) {
        override fun matchesSafely(textView: TextView): Boolean {

            val actualColor = (textView.getBackground() as GradientDrawable).color?.defaultColor
            return expectedColor == actualColor
        }

        override fun describeTo(description: Description) {
            description.appendText("with background color: $expectedColor")
        }
    }
}
于 2020-05-12T12:28:56.357 回答