Espresso test with “hasBackground”

China☆狼群 提交于 2020-01-03 02:22:15

问题


How can I make a espresso test with the color of the layout background? Currently use hasBackground():

onView(withId(R.id.backgroundColor)).check(matches(hasBackground(Color.parseColor("#FF55ff77"))));

But the error occurs:

android.support.test.espresso.base.DefaultFailureHandler$AssertionFailedWithCauseError: 'has background with drawable ID: -11141257' doesn't match the selected view.

Expected: has background with drawable ID: -11141257

Got: "LinearLayout{id=2130968576, res-name=backgroundColor, visibility=VISIBLE, width=996, height=1088, has-focus=false, has-focusable=false, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, layout-params=android.widget.LinearLayout$LayoutParams@e55f6e7, tag=null, root-is-layout-requested=false, has-input-connection=false, x=42.0, y=601.0, child-count=2}"

How I can compare this?


回答1:


I'm doing it with a custom matcher with the help of Hamcrest lib :

public class BackgroundColourMatcher extends TypeSafeMatcher<View> {

    @ColorRes
    private final int mExpectedColourResId;

    private int mColorFromView;

    public BackgroundColourMatcher(@ColorRes int expectedColourResId) {
        super(View.class);
        mExpectedColourResId = expectedColourResId;
    }

    @Override
    protected boolean matchesSafely(View item) {

        if (item.getBackground() == null) {
            return false;
        }
        Resources resources = item.getContext().getResources();
        int colourFromResources = ResourcesCompat.getColor(resources, mExpectedColourResId, null);
        mColorFromView = ((ColorDrawable) item.getBackground()).getColor();
        return mColorFromView == colourFromResources;
    }

    @Override
    public void describeTo(Description description) {
        description.appendText("Color did not match " + mExpectedColourResId + " was " + mColorFromView);
    }
}

And you can provide your matcher with something like:

public class CustomTestMatchers {

    public static Matcher<View> withBackgroundColour(@ColorRes int expectedColor) {
        return new BackgroundColourMatcher(expectedColor);
    }
}

And finally in your test:

onView(withId(R.id.my_view)).check(matches(withBackgroundColour(R.color.color_to_check)))

You can easily modify the BackgroundColourMatcher class to make it use directly a colour and not a resource.

Hope it helps!




回答2:


Another way of doing it is simply retrieving the color value directly from the View:

val bar = activityRule.activity.findViewById<View>(R.id.backgroundColor)
val actualColor = (bar.background as ColorDrawable).color
val expectedColor = Color.parseColor("#FF55ff77")
assertEquals(actualColor, expectedColor)


来源:https://stackoverflow.com/questions/47417240/espresso-test-with-hasbackground

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!