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.

你可能感兴趣的:(Build a simple UiAutomator 2.0 test in Android Studio)