【发布时间】:2020-08-27 15:30:43
【问题描述】:
我已经像这样以编程方式设置了 GradientDrawable 背景,并且正在尝试测试它的颜色。主要问题似乎是在测试时从形状 (GradientDrawable) 中获取颜色。
这个 sn-p 来自一个更大的绑定适配器..
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
【问题讨论】:
标签: unit-testing kotlin gradientdrawable