Select Date from Calendar in Android Espresso

前端 未结 1 2034
梦如初夏
梦如初夏 2021-01-02 09:02

I am testing an Android app with Espresso. I have an EditText widget with androidInputType=date. When I touch this control with my finger, a cale

相关标签:
1条回答
  • 2021-01-02 09:35

    Original answered by me here, but in the scope of another question: Recording an Espresso test with a DatePicker - so I repost my adapted answer from there:

    Use this line to set the date in a datepicker:

    onView(withClassName(Matchers.equalTo(DatePicker.class.getName()))).perform(PickerActions.setDate(year, monthOfYear, dayOfMonth));
    

    This uses the PickerActions which is part of the espresso support library - the espresso-contrib. To use it, add it like this to your gradle file (You need several excludes to prevent compile errors due to mismatching support library version):

    androidTestCompile('com.android.support.test.espresso:espresso-contrib:2.2.2') {
        exclude group: 'com.android.support', module: 'appcompat'
        exclude module: 'support-annotations'
        exclude module: 'support-v4'
        exclude module: 'support-v13'
        exclude module: 'recyclerview-v7'
        exclude module: 'appcompat-v7'
    }
    

    Then you could create a helper method which clicks the view that opens the datepicker, sets the date and confirms it by clicking the ok button:

    public static void setDate(int datePickerLaunchViewId, int year, int monthOfYear, int dayOfMonth) {
        onView(withParent(withId(buttonContainer)), withId(datePickerLaunchViewId)).perform(click());
        onView(withClassName(Matchers.equalTo(DatePicker.class.getName()))).perform(PickerActions.setDate(year, monthOfYear, dayOfMonth));
        onView(withId(android.R.id.button1)).perform(click());
    }
    

    And then use it like this in your tests:

    TestHelper.setDate(R.id.date_button, 2017, 1, 1); 
    //TestHelper is my helper class that contains the helper method above
    
    0 讨论(0)
提交回复
热议问题