Android UIAutomator with Kotlin

Andres Sandoval
2 min readOct 4, 2018

UIAutomator it’s similar to Espresso, but with UIAutomator you can automate tests outside and inside of the app. The code below shows how to do clicks and scroll on Android device settings. The test opens the device settings and clicks to reset the Google advertising ID. Look at the demo video at the bottom.

How to run:

  1. Add the “UIAutomator” Gradle dependency in your file build.gradle.
dependencies {
...
androidTestImplementation 'androidx.test.uiautomator:uiautomator:2.2.0'
}
  1. In androidTest directory create a new Kotlin class UIAutomatorDemo.
  2. Copy and Paste below code.
  3. Run.
  4. The test: Opens the device settings and clicks to reset the Google advertising ID.
package your.app.name

import android.support.test.InstrumentationRegistry
import android.support.test.filters.SdkSuppress
import android.support.test.runner.AndroidJUnit4
import android.support.test.uiautomator.By
import android.support.test.uiautomator.UiDevice
import android.support.test.uiautomator.UiScrollable
import android.support.test.uiautomator.UiSelector
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
@SdkSuppress(minSdkVersion = 18)
class UIAutomatorDemo {

companion object {
const val GOOGLE_SETTING = "Google"
const val ADS_SETTING = "Ads"
const val RESET_ADVERTISING_ID = "Reset advertising ID"
}

@Test
fun resetAdvertisingID() {
val mDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation())
mDevice.pressHome()

val appsList = mDevice.findObject(UiSelector().descriptionContains("Apps list"))
appsList.click()
//Click on Google setting
val clickSettings = mDevice.findObject(By.desc("Settings"))
clickSettings.click()

val appDrawer = UiScrollable(UiSelector().scrollable(true))
appDrawer.scrollForward()
appDrawer.scrollTextIntoView("$GOOGLE_SETTING")

val clickGoogle = mDevice.findObject(UiSelector().text("$GOOGLE_SETTING"))
clickGoogle.click()

//Click on Ads setting
val clickAds = mDevice.findObject(UiSelector().text("$ADS_SETTING"))
clickAds.click()

//Click on Reset advertising ID
val clickResetAdvertisingID = mDevice.findObject(UiSelector().text("$RESET_ADVERTISING_ID"))
clickResetAdvertisingID.click()

val clickOk = mDevice.findObject(UiSelector().text("OK"))
clickOk.click()
}
}

Demo:

Resources:

UIatomator Kotlin API

solution

Thanks for reading! If you like the post please give a clap.

--

--