1

レイアウトの背景色を使用してエスプレッソテストを行うにはどうすればよいですか?現在hasBackground()使用:「hasBackground」を使用したエスプレッソ試験

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

をしかし、エラーが発生します。

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, [email protected], tag=null, root-is-layout-requested=false, has-input-connection=false, x=42.0, y=601.0, child-count=2}"

私はこれを比較することができますどのように?

答えて

2

私は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); 
    } 
} 

そして、あなたのようなものを使用して、整合を提供することができます。

テストで
public class CustomTestMatchers { 

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

そして最後に:

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

BackgroundColourMatcherクラスを使用して、リソースではなく色を直接使用するようにします。

希望すると助かります!

関連する問題