在 Espresso 中获取按钮背景颜色

Getting button background color in Espresso

我正在尝试借助这个 Matcher 获取按钮背景颜色。

    public static Matcher<View> withButtonColor(int expectedColor) {

    return new BoundedMatcher<View, Button>(Button.class) {
        @Override
        public boolean matchesSafely(Button button) {
            int actualColor = 0;
            try {
                actualColor = ContextCompat.getColor(currentActivity.getBaseContext(), expectedColor);
            } catch (Exception e) {
                e.printStackTrace();
            }

            return expectedColor == actualColor;

        }

        @Override
        public void describeTo(Description description) {
            description.appendText("ERROR");
        }
    };
}

正在使用

onView(withId(trueButton)).check(matches(withButtonColor(ActivityPage.greenColor)));

虽然没有什么帮助。

我传递了一个有效的颜色作为参数,尽管实际颜色总是等于 0。 我想获取上下文可能有问题。

您的自定义 ViewMatcher 看起来不错。

尝试更改:

currentActivity.getBaseContext()

对于:

InstrumentationRegistry.getInstrumentation().getTargetContext()

作为上下文参数。