Build a simple UiAutomator 2.0 test in Android Studio

Note:I wrote this just to remind myself, in case I may forget it myself .

  • Open Android Studio,create a new project .
  • Choose a project name,for example : Scan .
  • Choose a company domain,for example : marvell.com . (so the package name is "com.marvell.scan")
  • Modify "build.gradle(app)",solve the conflict and do sync .For example :
apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.1"
    defaultConfig {
        applicationId "com.marvell.scan"
        minSdkVersion 21
        targetSdkVersion 23
        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'])
    compile 'com.android.support:appcompat-v7:23.1.0'
    compile 'com.android.support:support-annotations:23.1.1'
    testCompile 'junit:junit:4.12'

    // Add UIAutomator 2.0 dependency
    androidTestCompile 'com.android.support:support-annotations:23.1.1'
    androidTestCompile 'com.android.support.test:runner:0.5'
    // Set this dependency to use JUnit 4 rules
    androidTestCompile 'com.android.support.test:rules:0.5'
    // Set this dependency to build and run UI Automator tests
    androidTestCompile 'com.android.support.test.uiautomator:uiautomator-v18:2.1.2'
}

  • In "java-com.marvell.scan(androidTest)",make a new class .
  • Add "@RunWith(AndroidJUnit4.class)" just before the class .
@RunWith(AndroidJUnit4.class)
public class testScanResult {
}
  • Place the cursor where you want a new test method to be generated ,press ALT+INSERT and select method from the menu .
@RunWith(AndroidJUnit4.class)
public class testScanResult {
    @BeforeClass
    public static void setUpBeforeClass() throws Exception {
        

    }

    @Test
    public void testBluetooth() throws Exception {

    }

    @Test
    public void testWifi() throws Exception {

    }

    @AfterClass
    public static void tearDownAfterClass() throws Exception {
        

    }
    
}
  • Add this before the "@BeforeClass" method :
@RunWith(AndroidJUnit4.class)
public class testScanResult {
    
    Instrumentation instrumentation;
    UiDevice myUiDevice;
    
    @BeforeClass
    public static void setUp() throws Exception {


    }

  • Add this to the "@BeforeClass" method :
    @BeforeClass
    public static void setUp() throws Exception {
        instrumentation = InstrumentationRegistry.getInstrumentation();
        myUiDevice = UiDevice.getInstance(instrumentation);
        myUiDevice.pressHome();
    }
  • Write test code .
@RunWith(JUnit4.class)
public class testWifi {
    static Instrumentation instrumentation;
    static UiDevice myUiDevice;
    static String enterWifiSetting = "am start -W com.android.tv.settings/.connectivity.NetworkActivity";
    static String killSettings = "am force-stop com.android.tv.settings";
    static int short_wait = 2000;
    static int maxScrollStep = 100;
    static String TAG_scan = "scanwifibt";

    @BeforeClass
    public static void setUpBeforeClass() throws IOException, UiObjectNotFoundException, InterruptedException {
        instrumentation = InstrumentationRegistry.getInstrumentation();
        myUiDevice = UiDevice.getInstance(instrumentation);
        myUiDevice.executeShellCommand(killSettings);
        myUiDevice.pressHome();
        myUiDevice.executeShellCommand(enterWifiSetting);
        UiObject2 wifiOnOff = myUiDevice.findObject(By.text("Wi-Fi")).getParent().getParent();
        if (myUiDevice.hasObject(By.text("Available networks"))){
            Log.i(TAG_scan, "testWifi: Wifi is already ON");
        }else {
            wifiOnOff.click();
            Log.i(TAG_scan, "testWifi: Wifi is OFF,turn it ON");
        }
        UiScrollable listAll = new UiScrollable(new UiSelector().scrollable(true));
        listAll.scrollToBeginning(maxScrollStep);
        if (myUiDevice.hasObject(By.text("See all"))){
            Log.i(TAG_scan, "testWifi: Find 'See all'");
        } else {
            for (int num = 1;num <= maxScrollStep;num++){
                boolean scrolled = listAll.scrollForward();
                if(myUiDevice.hasObject(By.text("See all"))) {
                    Log.i(TAG_scan, "testWifi: Find 'See all'");
                    break;
                }
                if (!scrolled) {
                    Log.i(TAG_scan, "testWifi: Already scrolled to the end,do not find 'See all'");
                    break;
                }
            }
        }
        UiObject2 seeAll = myUiDevice.findObject(By.text("See all")).getParent().getParent();
        if (seeAll.isClickable()){
            seeAll.click();
            Log.i(TAG_scan, "testWifi: Click 'See all'");
        }else {
            Log.w(TAG_scan, "testWifi: 'See all' cannot be clicked");
        }
        Thread.sleep(short_wait);
    }

    @Test
    public void testWifi_5g() throws UiObjectNotFoundException {
        UiScrollable wifiList = new UiScrollable(new UiSelector().scrollable(true));
        wifiList.setAsVerticalList();
        Boolean flag01 = wifiList.scrollIntoView(new UiSelector().text("Linksys44296_5GHz"));
        Log.i(TAG_scan, "testWifi: 5g Wifi is available,flag01 = "+flag01);
        //!!!Already tested,assert() is NOT reliable!!!
        if (!flag01){
            fail();
        }
    }

    @Test
    public void testWifi_24g() throws UiObjectNotFoundException {
        UiScrollable wifiList = new UiScrollable(new UiSelector().scrollable(true));
        wifiList.setAsVerticalList();
        Boolean flag02 = wifiList.scrollIntoView(new UiSelector().text("Linksys44296"));
        Log.i(TAG_scan, "testWifi: 2.4g Wifi is available,flag02="+flag02);
        if (!flag02){
            fail();
        }
    }

    @AfterClass
    public static void tearDownAfterlass() throws Exception {
        myUiDevice.pressHome();
    }
}
@RunWith(JUnit4.class)
public class testBluetooth {
    Instrumentation instrumentation;
    UiDevice myUiDevice;
    String killSettings = "am force-stop com.android.tv.settings";
    String scanBluetooth = "am start -W com.android.tv.settings/.accessories.AddAccessoryActivity";
    String TAG_scan = "scanwifibt";
    int waitTime_Bluetooth = 120000;

    @Before
    public void setUp() throws IOException {
        instrumentation = InstrumentationRegistry.getInstrumentation();
        myUiDevice = UiDevice.getInstance(instrumentation);
        myUiDevice.pressHome();
        myUiDevice.executeShellCommand(killSettings);
        myUiDevice.executeShellCommand(scanBluetooth);
    }

    @Test
    public void testBT() throws AssertionError, InterruptedException {
        myUiDevice.wait(Until.hasObject(By.res("com.android.tv.settings:id/list")),waitTime_Bluetooth);
        Thread.sleep(3000);
        UiObject2 BTList = myUiDevice.findObject(By.res("com.android.tv.settings:id/list"));
        Log.i(TAG_scan, "testWifi: Available BT device number is "+BTList.getChildCount());
        //!!!Already tested,assert() is NOT reliable!!!
        if (!(BTList.getChildCount() >= 1)){
            fail();
        }
    }

    @After
    public void tearDown() throws Exception {
        myUiDevice.pressHome();
    }
}
  • Create a test suite .
package com.marvell.scan;

import org.junit.runner.RunWith;
import org.junit.runners.Suite;

/**
 * Created by Zishang on 2017/2/9.
 */
@RunWith(Suite.class)
@Suite.SuiteClasses({
        testBluetooth.class,
        testWifi.class
}
)
public class testAll {
}

The code is here.

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末且轨,一起剝皮案震驚了整個濱河市比默,隨后出現(xiàn)的幾起案子禁荒,更是在濱河造成了極大的恐慌,老刑警劉巖缰儿,帶你破解...
    沈念sama閱讀 212,454評論 6 493
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異泌参,居然都是意外死亡步悠,警方通過查閱死者的電腦和手機签杈,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,553評論 3 385
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來鼎兽,“玉大人答姥,你說我怎么就攤上這事铣除。” “怎么了踢涌?”我有些...
    開封第一講書人閱讀 157,921評論 0 348
  • 文/不壞的土叔 我叫張陵,是天一觀的道長序宦。 經(jīng)常有香客問我睁壁,道長,這世上最難降的妖魔是什么互捌? 我笑而不...
    開封第一講書人閱讀 56,648評論 1 284
  • 正文 為了忘掉前任潘明,我火速辦了婚禮,結(jié)果婚禮上秕噪,老公的妹妹穿的比我還像新娘钳降。我一直安慰自己,他們只是感情好腌巾,可當(dāng)我...
    茶點故事閱讀 65,770評論 6 386
  • 文/花漫 我一把揭開白布遂填。 她就那樣靜靜地躺著,像睡著了一般澈蝙。 火紅的嫁衣襯著肌膚如雪吓坚。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 49,950評論 1 291
  • 那天灯荧,我揣著相機與錄音礁击,去河邊找鬼。 笑死逗载,一個胖子當(dāng)著我的面吹牛哆窿,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播厉斟,決...
    沈念sama閱讀 39,090評論 3 410
  • 文/蒼蘭香墨 我猛地睜開眼挚躯,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了擦秽?” 一聲冷哼從身側(cè)響起秧均,我...
    開封第一講書人閱讀 37,817評論 0 268
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎号涯,沒想到半個月后目胡,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 44,275評論 1 303
  • 正文 獨居荒郊野嶺守林人離奇死亡链快,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 36,592評論 2 327
  • 正文 我和宋清朗相戀三年誉己,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片域蜗。...
    茶點故事閱讀 38,724評論 1 341
  • 序言:一個原本活蹦亂跳的男人離奇死亡巨双,死狀恐怖噪猾,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情筑累,我是刑警寧澤袱蜡,帶...
    沈念sama閱讀 34,409評論 4 333
  • 正文 年R本政府宣布,位于F島的核電站慢宗,受9級特大地震影響坪蚁,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜镜沽,卻給世界環(huán)境...
    茶點故事閱讀 40,052評論 3 316
  • 文/蒙蒙 一敏晤、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧缅茉,春花似錦嘴脾、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,815評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至拇颅,卻和暖如春扶平,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背蔬蕊。 一陣腳步聲響...
    開封第一講書人閱讀 32,043評論 1 266
  • 我被黑心中介騙來泰國打工结澄, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人岸夯。 一個月前我還...
    沈念sama閱讀 46,503評論 2 361
  • 正文 我出身青樓麻献,卻偏偏與公主長得像,于是被迫代替她去往敵國和親猜扮。 傳聞我的和親對象是個殘疾皇子勉吻,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 43,627評論 2 350

推薦閱讀更多精彩內(nèi)容

  • **2014真題Directions:Read the following text. Choose the be...
    又是夜半驚坐起閱讀 9,437評論 0 23
  • 站在時間新舊交接點齿桃,倉惶無措。 二零一六五步三顧首戀戀不舍煮盼,二零一七踏著急匆匆的步伐趕來短纵。至少我還...
    南冠閱讀 573評論 0 0
  • 很多事值不值得做,并不取決于別人怎樣看僵控,怎樣說香到,怎樣想。他們再有閱歷和經(jīng)驗,智商情商雙高悠就,也不能代替你做出決定千绪。很...
    冰咋吃閱讀 166評論 0 0
  • 昨天一篇《我愿意》稍稍安慰受傷的心,今天一天都有點沒精打采梗脾,努力調(diào)整荸型,腦子里細細回憶,想用過往美好的點滴讓...
    cf302fb8f796閱讀 256評論 1 0
  • 心依舊還是浮躁著,但是知道宇立,要靜下來踪宠,想想2017年的日子了自赔。小時候很開心過年妈嘹,可以收到壓歲錢,可以買新衣服绍妨,長大...
    元寶媽媽2013閱讀 146評論 0 0