Skip to content

Instantly share code, notes, and snippets.

@jeffypooo
Created April 24, 2016 23:31
Show Gist options
  • Save jeffypooo/fa32b23c79fd5267961e6e33bfd38694 to your computer and use it in GitHub Desktop.
Save jeffypooo/fa32b23c79fd5267961e6e33bfd38694 to your computer and use it in GitHub Desktop.
Hamcrest view matchers for Android + Robolectric
package com.beartooth.bronco;
import android.view.View;
import android.widget.TextView;
import org.hamcrest.BaseMatcher;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
/**
* Hamcrest matchers for Android views (useful with Robolectric)
*/
public class ViewMatchers {
public static Matcher<? super View> isView(final int viewId) {
return new BaseMatcher<View>() {
@Override
public boolean matches(Object item) {
return ((View) item).getId() == viewId;
}
@Override
public void describeTo(Description description) {
description.appendText("expecting view id: " + viewId);
}
@Override
public void describeMismatch(Object item, Description description) {
description.appendText("but was " + ((View) item).getId());
}
};
}
public static <T extends TextView> Matcher<? super TextView> hasText(final String expected) {
return new BaseMatcher<TextView>() {
@Override
public boolean matches(Object item) {
return ((TextView) item).getText().toString().equals(expected);
}
@Override
public void describeTo(Description description) {
description.appendText("expected view text: \"" + expected + "\"");
}
@Override
public void describeMismatch(Object item, Description description) {
description.appendText("but was \"" + ((TextView) item).getText().toString() + "\"");
}
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment