无法在 Hamcrest Matcher 中获取上下文

Can't get context in Hamcrest Matcher

这是我的 Espresso 测试:

 @Test
    fun buttonStartBackgroundColor() {
        onView(withId(R.id.startButton)).check(matches(withBackgroundColorResId(R.color.colorAccent)));
    }

这是我的自定义 Hamcrest 匹配器:

import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;
import androidx.test.espresso.matcher.BoundedMatcher
import androidx.test.espresso.matcher.ViewMatchers.isAssignableFrom
import androidx.vectordrawable.graphics.drawable.VectorDrawableCompat

object CustomMatchers {
    private val TAG = CustomMatchers::class.java.name

    fun withBackgroundColorResId(expectedId: Int): Matcher<View> {

            return object : BoundedMatcher<View, ViewGroup>(ViewGroup::class.java) {
                override fun matchesSafely(view: ViewGroup): Boolean {
                    val color = (view.background.current as ColorDrawable).color
                    return color == ContextCompat.getColor(view.context, expectedId)
                }

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

测试失败并显示消息:

androidx.test.espresso.base.DefaultFailureHandler$AssertionFailedWithCauseError: 'with background color: <2131034155>' doesn't match the selected view.
Expected: with background color: <2131034155>

但是这条消息不是人类可读的。 所以我想重写方法 describeTo 来获取人类可读的文本。像这样:

override fun describeTo(description: Description) {
                description.appendText("with background color: ")
                description.appendValue(ContextCompat.getColor(getResources(), expectedId))
            }

但由于无法解析 getResources(),我收到编译错误。我需要 android 上下文来解决这个问题。

如何获取方法中的上下文 describeTo

您应该使用以下方法来获取您需要的上下文:

InstrumentationRegistry.getInstrumentation().context // for test application context
InstrumentationRegistry.getInstrumentation().targetContext // for application under test context

参见示例 here