Espresso UI Test

Add dependencies

 //UI Test
    androidTestImplementation 'androidx.test:runner:1.1.0-alpha4'
    androidTestImplementation 'androidx.test:rules:1.1.0-alpha4'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.0-alpha4'
    androidTestImplementation 'androidx.test.espresso:espresso-contrib:3.1.0-alpha4'

    testImplementation 'junit:junit:4.12'

contrib  for reyclerView test

Test Basic

1.Create TestFile , ex : RecordActivity , UITestFile -> RecordActivityTest

2.Function basic framework

import androidx.test.rule.ActivityTestRule;
import androidx.test.runner.AndroidJUnit4;
import org.junit.Rule;
import org.junit.runner.RunWith;

@RunWith(AndroidJUnit4.class)
public class RecordActivityTest {
    
    @Rule
    public ActivityTestRule activityTestRule = new ActivityTestRule(RecordActivity.class);
    
    
}

3.Every testfunction need add @Test

@Test
    public void viewsTest(){
        
    }

Test work flow

1.check All Views exist  ?

2.check click event is ok ?

3.if have recyclerView , item click is ok ?

4. show alert is ok ?

5. show result is equal ?

onView:藉由ViewMatchers.withId 找出 View

import androidx.test.espresso.Espresso;
import androidx.test.espresso.matcher.ViewMatchers;

@Test 
public void viewsTest(){ 
     Espresso.onView(ViewMatchers.withId(0)); 
}

再繼續點 會有

perform(ViewActions) : click , clearText …

check(ViewAssertions) : isDisplayed() ..

@Test
    public void viewsTest(){
        Espresso.onView(ViewMatchers.withId(0)).perform(ViewActions.click());
        Espresso.onView(ViewMatchers.withId(0)).check(ViewAssertions.matches(ViewMatchers.isDisplayed()));
    }

RecycleView UI Test

onView(withId(id)).perform(RecyclerViewActions.actionOnItemAtPosition(CLICK_ITEM,click()));

RecyclerViewActions have more actions

reference : https://imsardine.github.io/2017/06/23/espresso-interact-with-verify-item-child-views/

if code to long , can import target method

import static androidx.test.espresso.Espresso.onView;
import static androidx.test.espresso.action.ViewActions.click;
import static androidx.test.espresso.assertion.ViewAssertions.matches;
import static androidx.test.espresso.matcher.ViewMatchers.withId;

Reference :

https://imsardine.github.io/2017/06/23/espresso-interact-with-verify-item-child-views/

https://developer.android.com/training/testing/espresso

最後修改日期: 2019-04-30 18:53:59

作者

留言

撰寫回覆或留言

發佈留言必須填寫的電子郵件地址不會公開。

這個網站採用 Akismet 服務減少垃圾留言。進一步瞭解 Akismet 如何處理網站訪客的留言資料