2013年11月26日火曜日

Espresso で Preference をクリックさせる

Matcher 書かないとダメっぽかったです。
PreferenceMatcher が用意されていたので利用しました。
  1. import static com.google.common.base.Preconditions.checkNotNull;  
  2. ...  
  3.   
  4. public class EspressoTest extends ActivityInstrumentationTestCase2<MainPreferenceActivity> {  
  5.   
  6.     public EspressoTest() {  
  7.         super(MainPreferenceActivity.class);  
  8.     }  
  9.   
  10.     @Override  
  11.     public void setUp() throws Exception {  
  12.         super.setUp();  
  13.         // Espresso will not launch our activity for us, we must launch it via  
  14.         // getActivity().  
  15.         getActivity();  
  16.     }  
  17.   
  18.     // Preference のキーを指定して、対応するビューをクリックする  
  19.     public void testPreference() {  
  20.         onData(withPreferenceKey("pref-key")).perform(click());  
  21.     }  
  22.   
  23.     public static Matcher<Object> withPreferenceKey(final Matcher<Preference> preferenceMatcher) {  
  24.         checkNotNull(preferenceMatcher);  
  25.         return new BoundedMatcher<Object, Preference>(Preference.class) {  
  26.   
  27.             @Override  
  28.             public void describeTo(Description description) {  
  29.                 description.appendText("with preference key: ");  
  30.                 preferenceMatcher.describeTo(description);  
  31.             }  
  32.   
  33.             @Override  
  34.             protected boolean matchesSafely(Preference pref) {  
  35.                 return preferenceMatcher.matches(pref);  
  36.             }  
  37.         };  
  38.     }  
  39.   
  40.     public static Matcher<Object> withPreferenceKey(String expectedText) {  
  41.         checkNotNull(expectedText);  
  42.         return withPreferenceKey(PreferenceMatchers.withKey(expectedText));  
  43.     }  
  44. }  


応用で、Preference をクリック → なんかする → summary が適切な値になっていることをチェック
  1. public void testPreference() {  
  2.     // Preference をクリック  
  3.     onData(withPreferenceKey("pref-key")).perform(click());  
  4.   
  5.     // クリック先でごにょごにょ  
  6.   
  7.     // summary が適切な値になっていることをチェック  
  8.     // summary の Id が android.R.id.summary であることを利用  
  9.     onData(withPreferenceKey("pref-key"))  
  10.         .onChildView(withId(android.R.id.summary))  
  11.         .check(matches(withText("correct summary value")));  
  12. }  



0 件のコメント:

コメントを投稿