Home | History | Annotate | Download | only in matchers
      1 package com.xtremelabs.robolectric.matchers;
      2 
      3 import android.view.View;
      4 import org.hamcrest.Description;
      5 import org.hamcrest.Factory;
      6 import org.hamcrest.Matcher;
      7 import org.junit.internal.matchers.TypeSafeMatcher;
      8 
      9 import static com.xtremelabs.robolectric.Robolectric.shadowOf;
     10 
     11 public class ViewHasTextMatcher<T extends View> extends TypeSafeMatcher<T> {
     12     private String expected;
     13     private int expectedResourceId;
     14     private String actualText;
     15 
     16     public ViewHasTextMatcher(String expected) {
     17         this.expected = expected;
     18         expectedResourceId = -1;
     19     }
     20 
     21     public ViewHasTextMatcher(int expectedResourceId) {
     22         this.expected = null;
     23         this.expectedResourceId = expectedResourceId;
     24     }
     25 
     26     @Override
     27     public boolean matchesSafely(View actual) {
     28         if (actual == null) {
     29             return false;
     30         }
     31 
     32         if (expectedResourceId != -1) {
     33             expected = actual.getContext().getResources().getString(expectedResourceId);
     34         }
     35 
     36         final CharSequence charSequence = shadowOf(actual).innerText();
     37         if (charSequence == null || charSequence.toString() == null) {
     38             return false;
     39         }
     40         actualText = charSequence.toString();
     41 
     42         return actualText.equals(expected);
     43     }
     44 
     45     @Override
     46     public void describeTo(Description description) {
     47         description.appendText("[" + actualText + "]");
     48         description.appendText(" to equal ");
     49         description.appendText("[" + expected + "]");
     50     }
     51 
     52 
     53     @Factory
     54     public static <T extends View> Matcher<T> hasText(String expectedTextViewText) {
     55         return new ViewHasTextMatcher<T>(expectedTextViewText);
     56     }
     57 
     58     @Factory
     59     public static <T extends View> Matcher<T> hasText(int expectedTextViewResourceId) {
     60         return new ViewHasTextMatcher<T>(expectedTextViewResourceId);
     61     }
     62 }
     63