上篇對UI Automator做了一個大概的敘述舱沧,這篇就講講怎么搭建一個UI Automator項目的測試環(huán)境齿兔。
1.打開Android Studio。(Android Studio環(huán)境怎么搭建可以自己百度查查)
2.點擊新建項目饲鄙,我這邊新建的項目名字叫Test门扇。(這里需要注意我們要建立的項目是沒有任何activity)
3.然后一直Next,等待整個項目建立起來地淀。
4.項目建立起來失球,然后點擊左側(cè)上面的視圖曾,選擇項目為Project帮毁。然后我們看到的視圖層應(yīng)該是下面圖片這種的实苞。
5.我們可以看到app → src 下面有三個包,分別的是androidTest烈疚,main黔牵,test。三個包里面我們用到的就是androidTest爷肝。
6.展開androidTest的包猾浦。如下圖陆错。會發(fā)現(xiàn)里面有3個層級了,一個自帶的Java包金赦,還有一個自帶的包名和一個類文件音瓷。
7.這個時候我們可以刪除他的包名,建立自己的包名和類名夹抗。
8.建立好之后绳慎,我們應(yīng)該添加我們需要做測試的依賴了。在app → build.gradle里面添加上我們所需要的依賴和sdk版本漠烧。然后點擊Sync杏愤。同步一下(這里我們需要注意下,minSdkVersion 18
這里UI Automator支持的sdk最低版本是18)
apply plugin: 'com.android.application'
android {
compileSdkVersion 26
buildToolsVersion "26.0.0"
defaultConfig {
applicationId "com.example.user.test"
minSdkVersion 18
targetSdkVersion 26
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:26.0.0-alpha1'
compile 'com.android.support:support-annotations:26.0.0-alpha1'
androidTestCompile 'com.android.support:support-annotations:26.0.0-alpha1'
androidTestCompile 'com.android.support.test:runner:0.5'
androidTestCompile 'com.android.support.test:rules:0.5'
androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.2'
androidTestCompile 'com.android.support.test.uiautomator:uiautomator-v18:2.1.2'
}
9.然后回到剛才我們建的類里面寫上以下代碼:
package Test;
import android.app.Instrumentation;
import android.content.Context;
import android.content.Intent;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import android.support.test.uiautomator.UiDevice;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.io.IOException;
@RunWith(AndroidJUnit4.class)
public class Tester {
static Instrumentation instrumentation;
static UiDevice mDevice;
@BeforeClass //也可以是Before
public static void setUpBeforeClass() throws IOException {
instrumentation = InstrumentationRegistry.getInstrumentation();
mDevice = UiDevice.getInstance(instrumentation);
}
@Test
public void test_Template() throws IOException, InterruptedException {
//啟動apk的程序
Context context = InstrumentationRegistry.getInstrumentation().getContext();
Intent intent = context.getPackageManager().getLaunchIntentForPackage("這里填的是包名");
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
context.startActivity(intent);
//下面寫你的邏輯代碼
}
@AfterClass //也可以是After
public static void tearDownAfterClass() throws IOException {
}
}
這個是一個UI Automator代碼的模板已脓,可以參考一下声邦。
下一篇我會介紹before,beforeclass摆舟,after,afterclass的區(qū)別邓了。還有UI Automator里面怎么實現(xiàn)截屏恨诱,截屏出問題了該怎么辦?
第一次寫博客骗炉,寫的不怎么好照宝,條理也不是很清楚的。如果有什么寫的不好的地方大家可以指出來句葵。我會隨時不定期的修改博客的厕鹃。