我已经像这样通过编程设置了一个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
我在网站上看到了一些关于类似问题的帖子,
但是似乎没有一个是有效的,并且大多数都以同样的问题结束。例如Testing background color espresso Android
或者答案似乎过时了,或者受到java到kotlin转换的影响..例如how to get the color from GradientDrawable
发布于 2020-05-12 12:28:56
我想出了一个解决办法,使用片段方案来访问“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")
}
}
}
https://stackoverflow.com/questions/61740752
复制相似问题