Android Studio Espresso測試配置

Espresso是Google自家的一個UI測試框架,雖然沒有推出正式版,但是目前已經是可用的了。優點是語法非常簡單,缺點還是隻能支持本應用內部測試。
如果你只是想要一個簡單的UI自動化測試框架,Espresso是個不錯的選擇。

其他網友的Espresso簡單介紹

Gradle配置

因爲是自家的所以配置非常簡單。只需要在build.gradle文件進行配置即可。配置文件如下,注意的地方都標註了。配置好之後Sync Projct之後就可以使用了。

../app/build.gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 22
    buildToolsVersion "22.0.1"

    defaultConfig {
        applicationId "com.example.espressotest"
        minSdkVersion 15
        targetSdkVersion 22
        versionCode 1
        versionName "1.0"

        //set test runer
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }

    packagingOptions{
        exclude 'LICENSE.txt'
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:22.0.0'
    // Testing-only dependencies
    androidTestCompile 'com.android.support.test:testing-support-lib:0.1'
    androidTestCompile 'com.android.support.test.espresso:espresso-core:2.0'
}

測試實例

測試類位置爲..app/src/androidTest/java/packagename

package com.example.espressotest;

import static android.support.test.espresso.Espresso.*;

import static android.support.test.espresso.matcher.ViewMatchers.*;

import static android.support.test.espresso.assertion.ViewAssertions.*;

import android.support.test.espresso.action.ViewActions;
import android.test.ActivityInstrumentationTestCase2;

/**
 * onView(),matches()等方法都是靜態,所以這裏爲了方便使用使用靜態導入
 */
public class TextTest extends ActivityInstrumentationTestCase2<MainActivity> {

    private static String TAG = "TextTest";
    private Activity activity;

    public TextTest() {
        super(MainActivity.class);
    }

    public TextTest(Class<MainActivity> activityClass) {
        super(activityClass);
    }

    @Override
    protected void setUp() throws Exception {
        super.setUp();
        // 準備好測試的Activity
        // activity = getActivity();
        getActivity();
    }
    // 測試方法使用test開頭
    public void test_text() {
        String hello = getActivity().getResources().getString(R.string.hello_world);

        // 測試控件顯示內容
               onView(withId(R.id.textView)).check(matches(withText(hello)));
    }

    public void test_showing() {

// 測試控件隱藏顯示      
   onView(withId(R.id.textView)).check(matches(isDisplayed()));
    }

    public void test_enable() {
        // 測試控件是否可用  
         onView(withId(R.id.textView)).check(matches(isEnabled()));
    }

    public void test_DilogShowing() {
// 通過對話框控件來測試對話框是否顯示
        onView(withId(R.id.textView)).perform(ViewActions.click());

    // 也可以通過內容來對應控件,當然不能有內容相同的衝突
        onView(withText("dialog")).check(matches(isDisplayed()));
    }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章