在Hamcrest Matcher中无法获取上下文

时间:2019-04-05 13:00:17

标签: android android-espresso hamcrest

这是我的浓咖啡测试:

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

这是我自定义的Hamcrest Matcher:

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 context来解决这个问题。

如何在方法describeTo中获得上下文

1 个答案:

答案 0 :(得分:1)

您应使用以下方法获取所需的上下文:

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

请参见示例here