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.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,544评论 6 501
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,430评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,764评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,193评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,216评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,182评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,063评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,917评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,329评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,543评论 2 332
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,722评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,425评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,019评论 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,671评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,825评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,729评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,614评论 2 353

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,476评论 0 23
  • 站在时间新旧交接点,仓惶无措。 二零一六五步三顾首恋恋不舍,二零一七踏着急匆匆的步伐赶来。至少我还...
    南冠阅读 575评论 0 0
  • 很多事值不值得做,并不取决于别人怎样看,怎样说,怎样想。他们再有阅历和经验,智商情商双高,也不能代替你做出决定。很...
    冰咋吃阅读 169评论 0 0
  • 昨天一篇《我愿意》稍稍安慰受伤的心,今天一天都有点没精打采,努力调整,脑子里细细回忆,想用过往美好的点滴让...
    cf302fb8f796阅读 259评论 1 0
  • 心依旧还是浮躁着,但是知道,要静下来,想想2017年的日子了。小时候很开心过年,可以收到压岁钱,可以买新衣服,长大...
    元宝妈妈2013阅读 148评论 0 0