Не может получить контекст в Hamcrest Matcher - PullRequest
0 голосов
/ 05 апреля 2019

Вот мой тест эспрессо:

 @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, чтобы это исправить.

Как получить контекст в методе describeTo

1 Ответ

1 голос
/ 08 апреля 2019

Вы должны использовать следующие методы, чтобы получить нужный вам контекст:

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

См. Пример здесь .

...