Search code examples
androidandroid-espressohamcrest

Can't get context in Hamcrest Matcher


Here my Espresso test:

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

Here my custom 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)
                }
            }
        }
}

Test is fail with message:

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

But this message is not human readable. So I want to rewrite the method describeTo to get the human-readable text. Something like this:

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

but I get a compile error because can't resolve getResources(). I need android context to fix this.

How I can get the context in method describeTo


Solution

  • You should use below methods to get context you need:

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

    See example here.