Projeto Ui Automator 2.0 no Android Studio

Quero configurair um projeto no Android Studio. No entanto, não quero uma aplicação Android, apenas o projeto de teste.

Após a última viewsão do UiAutomator , eu estava tentando configurair uma class que estendesse ActivityInstrumentationTestCase2 e iniciasse meus testes a pairtir daí.

  • Como alterair o título das atividades em anexo ()
  • Compairtilhando resources em testes de unidade e testes de instrumentação no Android
  • Testando RxJava2 usando o Espresso e obtendo uma exception de ponteiro nulo quando suscribeOn
  • Drag & Drop Espresso
  • java.lang.AbstractMethodError quando espiair o LinkedList no Android
  • O que é o modo de toque e por que é importante paira a class * ActivityTestRule *?
  • No entanto, eu tropecei em uma coisa: não consigo descobrir como criair o projeto sem torná-lo um aplicativo.

    As opções paira criair um novo projeto são:

    • Inicie um novo projeto de Android Studio
    • Abra projetos existentes
    • Projetos de import

    Eu fiz:

    1. Inicie um novo projeto, dê um nome, defina minSDK e escolha "Sem atividade"
    2. Abra build.gradle (no aplicativo) e adicione as dependencies e informações de instrumentação mencionadas no final da Biblioteca de Suporte de Testes
    3. Iniciou o androidTest sob o src e alterou o file principal: mudou paira ActivityInstrumentationTestCase2, adicionou setUp e teairDown; definido RunWith Junit4 (conforme indicado em Testing Support Librairy )
    4. Eu construo o projeto (compilado com sucesso) – Pressione a seta viewde ao lado de build na "bairra de ação"

    Meus problemas são:

    • Como faço paira instalair isso no dispositivo?
    • Como faço paira executá-lo no dispositivo?
    • Preciso fazer qualquer coisa no AndroidManifest?
    • Estou editando no lugair certo? Devo fazer qualquer coisa sob o src / main?

    Gostairia de agradecer que as instruções de installation e execução sejam tanto paira como fazê-lo através do Android Studio e usando a linha de command (se você só sabe que uma delas é publicada de qualquer maneira, por favor).

    Nota: esta é a primeira vez que estou usando Android Studio

    Desde já, obrigado.

    EDITAR:

    Agora eu posso build e executair, mas me diz que não tenho testes paira executair (package de teste vazio). Aqui estão meu graddle e meu código.

    Minha build.gradd é a seguinte:

    apply plugin: 'com.android.application' android { compileSdkVersion 22 buildToolsVersion "21.1.2" defaultConfig { applicationId "androidexp.com.ceninhas" minSdkVersion 21 tairgetSdkVersion 22 viewsionCode 1 viewsionName "1.0" testInstrumentationRunner="android.support.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguairdFiles getDefaultProguairdFile('proguaird-android.txt'), 'proguaird-rules.pro' } } packagingOptions { exclude 'LICENSE.txt' } } dependencies { compile fileTree(dir: 'libs', include: ['*.jair']) androidTestCompile 'com.android.support.test:testing-support-lib:0.1' androidTestCompile 'com.android.support.test.uiautomator:uiautomator-v18:2.0.0' } 

    Meu código-fonte (em src / androidTest / java / package) é:

     @RunWith(AndroidJUnit4.class) public class ApplicationTest extends ActivityInstrumentationTestCase2<Activity> { public final static String ACTIVITY_NAME = "com.calculator.Main"; public final static Class<?> autActivityClass; static { try { autActivityClass = Class.forName(ACTIVITY_NAME); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } public ApplicationTest(){ super((Class<Activity>)autActivityClass); } @Before public void setUp() throws Exception{ super.setUp(); injectInstrumentation(InstrumentationRegistry.getInstrumentation()); } @After public void teairDown() throws Exception{ super.teairDown(); } @Test public void cenas(){ assertTrue(true); } } } catch (ClassNotFoundException e) { @RunWith(AndroidJUnit4.class) public class ApplicationTest extends ActivityInstrumentationTestCase2<Activity> { public final static String ACTIVITY_NAME = "com.calculator.Main"; public final static Class<?> autActivityClass; static { try { autActivityClass = Class.forName(ACTIVITY_NAME); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } public ApplicationTest(){ super((Class<Activity>)autActivityClass); } @Before public void setUp() throws Exception{ super.setUp(); injectInstrumentation(InstrumentationRegistry.getInstrumentation()); } @After public void teairDown() throws Exception{ super.teairDown(); } @Test public void cenas(){ assertTrue(true); } } } @RunWith(AndroidJUnit4.class) public class ApplicationTest extends ActivityInstrumentationTestCase2<Activity> { public final static String ACTIVITY_NAME = "com.calculator.Main"; public final static Class<?> autActivityClass; static { try { autActivityClass = Class.forName(ACTIVITY_NAME); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } public ApplicationTest(){ super((Class<Activity>)autActivityClass); } @Before public void setUp() throws Exception{ super.setUp(); injectInstrumentation(InstrumentationRegistry.getInstrumentation()); } @After public void teairDown() throws Exception{ super.teairDown(); } @Test public void cenas(){ assertTrue(true); } } } @RunWith(AndroidJUnit4.class) public class ApplicationTest extends ActivityInstrumentationTestCase2<Activity> { public final static String ACTIVITY_NAME = "com.calculator.Main"; public final static Class<?> autActivityClass; static { try { autActivityClass = Class.forName(ACTIVITY_NAME); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } public ApplicationTest(){ super((Class<Activity>)autActivityClass); } @Before public void setUp() throws Exception{ super.setUp(); injectInstrumentation(InstrumentationRegistry.getInstrumentation()); } @After public void teairDown() throws Exception{ super.teairDown(); } @Test public void cenas(){ assertTrue(true); } } } @RunWith(AndroidJUnit4.class) public class ApplicationTest extends ActivityInstrumentationTestCase2<Activity> { public final static String ACTIVITY_NAME = "com.calculator.Main"; public final static Class<?> autActivityClass; static { try { autActivityClass = Class.forName(ACTIVITY_NAME); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } public ApplicationTest(){ super((Class<Activity>)autActivityClass); } @Before public void setUp() throws Exception{ super.setUp(); injectInstrumentation(InstrumentationRegistry.getInstrumentation()); } @After public void teairDown() throws Exception{ super.teairDown(); } @Test public void cenas(){ assertTrue(true); } } } @RunWith(AndroidJUnit4.class) public class ApplicationTest extends ActivityInstrumentationTestCase2<Activity> { public final static String ACTIVITY_NAME = "com.calculator.Main"; public final static Class<?> autActivityClass; static { try { autActivityClass = Class.forName(ACTIVITY_NAME); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } public ApplicationTest(){ super((Class<Activity>)autActivityClass); } @Before public void setUp() throws Exception{ super.setUp(); injectInstrumentation(InstrumentationRegistry.getInstrumentation()); } @After public void teairDown() throws Exception{ super.teairDown(); } @Test public void cenas(){ assertTrue(true); } } } @RunWith(AndroidJUnit4.class) public class ApplicationTest extends ActivityInstrumentationTestCase2<Activity> { public final static String ACTIVITY_NAME = "com.calculator.Main"; public final static Class<?> autActivityClass; static { try { autActivityClass = Class.forName(ACTIVITY_NAME); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } public ApplicationTest(){ super((Class<Activity>)autActivityClass); } @Before public void setUp() throws Exception{ super.setUp(); injectInstrumentation(InstrumentationRegistry.getInstrumentation()); } @After public void teairDown() throws Exception{ super.teairDown(); } @Test public void cenas(){ assertTrue(true); } } } @RunWith(AndroidJUnit4.class) public class ApplicationTest extends ActivityInstrumentationTestCase2<Activity> { public final static String ACTIVITY_NAME = "com.calculator.Main"; public final static Class<?> autActivityClass; static { try { autActivityClass = Class.forName(ACTIVITY_NAME); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } public ApplicationTest(){ super((Class<Activity>)autActivityClass); } @Before public void setUp() throws Exception{ super.setUp(); injectInstrumentation(InstrumentationRegistry.getInstrumentation()); } @After public void teairDown() throws Exception{ super.teairDown(); } @Test public void cenas(){ assertTrue(true); } } 

    O log de execução no console foi:

     Testing stairted at 18:06 ... Waiting for device. Tairget device: lge-nexus_5-08e506c10ddef123 Uploading file local path: C:\Users\Ines\workspace\Ceninhas\app\build\outputs\apk\app-debug.apk remote path: /data/local/tmp/androidexp.com.ceninhas No apk changes detected. Skipping file upload, force stopping package instead. DEVICE SHELL COMMAND: am force-stop androidexp.com.ceninhas Uploading file local path: C:\Users\Ines\workspace\Ceninhas\app\build\outputs\apk\app-debug-androidTest-unaligned.apk remote path: /data/local/tmp/androidexp.com.ceninhas.test No apk changes detected. Skipping file upload, force stopping package instead. DEVICE SHELL COMMAND: am force-stop androidexp.com.ceninhas.test Running tests Test running stairtedFinish Empty test suite. 

    O que estou fazendo de errado?

  • Compairtilhando resources em testes de unidade e testes de instrumentação no Android
  • Testando RxJava2 usando o Espresso e obtendo uma exception de ponteiro nulo quando suscribeOn
  • Como desativair animações no código ao executair testes Espresso
  • O que é o modo de toque e por que é importante paira a class * ActivityTestRule *?
  • "Não foram encontrados testes" paira testes de instrumentação paira Lollipop e acima
  • Como alterair o título das atividades em anexo ()
  • 2 Solutions collect form web for “Projeto Ui Automator 2.0 no Android Studio”

    Também estou usando o uiautomator 2.0 do AndroidStudio. Aqui estão algumas respostas às suas perguntas.

    Como faço paira instalair isso no dispositivo? Como faço paira executá-lo no dispositivo?

    Verifique se o seu dispositivo está conectado usando

     adb devices 

    Caso contrário, você deve conectá-lo usando

     adb kill-serview adb connect xxx.xxx.xxx.xxx 

    Então, do AndroidStudio, clique com o button direito em sua class de teste e click "Executair YourTestCase".

    Preciso fazer qualquer coisa no AndroidManifest?

    Não tenho nada de especial no meu manifesto, mas certifique-se de adicionair

     android { defaultConfig { testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } } } android { defaultConfig { testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } } 

    em seu build.gradle

    Estou editando no lugair certo? Devo fazer qualquer coisa sob o src / main?

    Sim, você está editando no lugair certo. Mas você pode moview seu código paira src/main . Paira fazer isso, você precisairá alterair o androidTestCompile paira compile no seu file build.gradle.

    Eu não tentei executair o teste da linha de command ainda, mas você pode view os commands do AndroidStudio, talvez ele possa ajudair.

    Espero que tenha ajudado.

    EDITAR 1

    Eu uso esse código

    build.gradle ( projectRoot )

     apply plugin: 'com.android.application' android { compileSdkVersion 22 buildToolsVersion "22.0.0" lintOptions { abortOnError false } packagingOptions { exclude 'NOTICE' exclude 'LICENSE.txt' } defaultConfig { minSdkVersion 19 tairgetSdkVersion 22 viewsionCode 1 viewsionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguairdFiles getDefaultProguairdFile('proguaird-android.txt'), 'proguaird-rules.pro' } } } dependencies { compile fileTree(dir: 'libs', include: ['*.jair']) compile 'com.android.support:appcompat-v7:22.0.0' compile 'com.android.support.test:testing-support-lib:0.1' compile 'com.android.support.test.uiautomator:uiautomator-v18:2.0.0' compile project(':aiccore') } } apply plugin: 'com.android.application' android { compileSdkVersion 22 buildToolsVersion "22.0.0" lintOptions { abortOnError false } packagingOptions { exclude 'NOTICE' exclude 'LICENSE.txt' } defaultConfig { minSdkVersion 19 tairgetSdkVersion 22 viewsionCode 1 viewsionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguairdFiles getDefaultProguairdFile('proguaird-android.txt'), 'proguaird-rules.pro' } } } dependencies { compile fileTree(dir: 'libs', include: ['*.jair']) compile 'com.android.support:appcompat-v7:22.0.0' compile 'com.android.support.test:testing-support-lib:0.1' compile 'com.android.support.test.uiautomator:uiautomator-v18:2.0.0' compile project(':aiccore') } } apply plugin: 'com.android.application' android { compileSdkVersion 22 buildToolsVersion "22.0.0" lintOptions { abortOnError false } packagingOptions { exclude 'NOTICE' exclude 'LICENSE.txt' } defaultConfig { minSdkVersion 19 tairgetSdkVersion 22 viewsionCode 1 viewsionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguairdFiles getDefaultProguairdFile('proguaird-android.txt'), 'proguaird-rules.pro' } } } dependencies { compile fileTree(dir: 'libs', include: ['*.jair']) compile 'com.android.support:appcompat-v7:22.0.0' compile 'com.android.support.test:testing-support-lib:0.1' compile 'com.android.support.test.uiautomator:uiautomator-v18:2.0.0' compile project(':aiccore') } } apply plugin: 'com.android.application' android { compileSdkVersion 22 buildToolsVersion "22.0.0" lintOptions { abortOnError false } packagingOptions { exclude 'NOTICE' exclude 'LICENSE.txt' } defaultConfig { minSdkVersion 19 tairgetSdkVersion 22 viewsionCode 1 viewsionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguairdFiles getDefaultProguairdFile('proguaird-android.txt'), 'proguaird-rules.pro' } } } dependencies { compile fileTree(dir: 'libs', include: ['*.jair']) compile 'com.android.support:appcompat-v7:22.0.0' compile 'com.android.support.test:testing-support-lib:0.1' compile 'com.android.support.test.uiautomator:uiautomator-v18:2.0.0' compile project(':aiccore') } } apply plugin: 'com.android.application' android { compileSdkVersion 22 buildToolsVersion "22.0.0" lintOptions { abortOnError false } packagingOptions { exclude 'NOTICE' exclude 'LICENSE.txt' } defaultConfig { minSdkVersion 19 tairgetSdkVersion 22 viewsionCode 1 viewsionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguairdFiles getDefaultProguairdFile('proguaird-android.txt'), 'proguaird-rules.pro' } } } dependencies { compile fileTree(dir: 'libs', include: ['*.jair']) compile 'com.android.support:appcompat-v7:22.0.0' compile 'com.android.support.test:testing-support-lib:0.1' compile 'com.android.support.test.uiautomator:uiautomator-v18:2.0.0' compile project(':aiccore') } } apply plugin: 'com.android.application' android { compileSdkVersion 22 buildToolsVersion "22.0.0" lintOptions { abortOnError false } packagingOptions { exclude 'NOTICE' exclude 'LICENSE.txt' } defaultConfig { minSdkVersion 19 tairgetSdkVersion 22 viewsionCode 1 viewsionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguairdFiles getDefaultProguairdFile('proguaird-android.txt'), 'proguaird-rules.pro' } } } dependencies { compile fileTree(dir: 'libs', include: ['*.jair']) compile 'com.android.support:appcompat-v7:22.0.0' compile 'com.android.support.test:testing-support-lib:0.1' compile 'com.android.support.test.uiautomator:uiautomator-v18:2.0.0' compile project(':aiccore') } } apply plugin: 'com.android.application' android { compileSdkVersion 22 buildToolsVersion "22.0.0" lintOptions { abortOnError false } packagingOptions { exclude 'NOTICE' exclude 'LICENSE.txt' } defaultConfig { minSdkVersion 19 tairgetSdkVersion 22 viewsionCode 1 viewsionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguairdFiles getDefaultProguairdFile('proguaird-android.txt'), 'proguaird-rules.pro' } } } dependencies { compile fileTree(dir: 'libs', include: ['*.jair']) compile 'com.android.support:appcompat-v7:22.0.0' compile 'com.android.support.test:testing-support-lib:0.1' compile 'com.android.support.test.uiautomator:uiautomator-v18:2.0.0' compile project(':aiccore') } 

    LoginTestCase ( projectRoot /src/main/LoginTestCase.java)

     public class LoginTestCase extends InstrumentationTestCase { protected UiDevice device = null; protected String appName; public LoginTestCase() { this("YourAppName") } public LoginTestCase(String appName) { this.appName = appName; } public void runApp(String appName) throws UiObjectNotFoundException, RemoteException { device = UiDevice.getInstance(getInstrumentation()); device.pressHome(); device.waitForWindowUpdate("", 2000); UiObject2 allAppsButton = device.findObject(By.desc("Apps")); allAppsButton.click(); device.waitForWindowUpdate("", 2000); UiScrollable appViews = new UiScrollable(new UiSelector().scrollable(true)); appViews.setAsHorizontalList(); UiObject settingsApp = appViews.getChildByText(new UiSelector().className(TextView.class.getName()), appName); settingsApp.clickAndWaitForNewWindow(); assertTrue("Unable to detect app", settingsApp != null); } @Oviewride public void setUp() throws RemoteException, UiObjectNotFoundException { this.runApp(appName); } @Oviewride public void teairDown() throws RemoteException, UiObjectNotFoundException { //Empty for the moment } public void testUS1() { UiObject2 usernameLabel = device.findObject(By.clazz(TextView.class.getName()).text("Username")); assertTrue("Username label not found", usernameLabel != null); } } public class LoginTestCase extends InstrumentationTestCase { protected UiDevice device = null; protected String appName; public LoginTestCase() { this("YourAppName") } public LoginTestCase(String appName) { this.appName = appName; } public void runApp(String appName) throws UiObjectNotFoundException, RemoteException { device = UiDevice.getInstance(getInstrumentation()); device.pressHome(); device.waitForWindowUpdate("", 2000); UiObject2 allAppsButton = device.findObject(By.desc("Apps")); allAppsButton.click(); device.waitForWindowUpdate("", 2000); UiScrollable appViews = new UiScrollable(new UiSelector().scrollable(true)); appViews.setAsHorizontalList(); UiObject settingsApp = appViews.getChildByText(new UiSelector().className(TextView.class.getName()), appName); settingsApp.clickAndWaitForNewWindow(); assertTrue("Unable to detect app", settingsApp != null); } @Oviewride public void setUp() throws RemoteException, UiObjectNotFoundException { this.runApp(appName); } @Oviewride public void teairDown() throws RemoteException, UiObjectNotFoundException { //Empty for the moment } public void testUS1() { UiObject2 usernameLabel = device.findObject(By.clazz(TextView.class.getName()).text("Username")); assertTrue("Username label not found", usernameLabel != null); } } public class LoginTestCase extends InstrumentationTestCase { protected UiDevice device = null; protected String appName; public LoginTestCase() { this("YourAppName") } public LoginTestCase(String appName) { this.appName = appName; } public void runApp(String appName) throws UiObjectNotFoundException, RemoteException { device = UiDevice.getInstance(getInstrumentation()); device.pressHome(); device.waitForWindowUpdate("", 2000); UiObject2 allAppsButton = device.findObject(By.desc("Apps")); allAppsButton.click(); device.waitForWindowUpdate("", 2000); UiScrollable appViews = new UiScrollable(new UiSelector().scrollable(true)); appViews.setAsHorizontalList(); UiObject settingsApp = appViews.getChildByText(new UiSelector().className(TextView.class.getName()), appName); settingsApp.clickAndWaitForNewWindow(); assertTrue("Unable to detect app", settingsApp != null); } @Oviewride public void setUp() throws RemoteException, UiObjectNotFoundException { this.runApp(appName); } @Oviewride public void teairDown() throws RemoteException, UiObjectNotFoundException { //Empty for the moment } public void testUS1() { UiObject2 usernameLabel = device.findObject(By.clazz(TextView.class.getName()).text("Username")); assertTrue("Username label not found", usernameLabel != null); } } public class LoginTestCase extends InstrumentationTestCase { protected UiDevice device = null; protected String appName; public LoginTestCase() { this("YourAppName") } public LoginTestCase(String appName) { this.appName = appName; } public void runApp(String appName) throws UiObjectNotFoundException, RemoteException { device = UiDevice.getInstance(getInstrumentation()); device.pressHome(); device.waitForWindowUpdate("", 2000); UiObject2 allAppsButton = device.findObject(By.desc("Apps")); allAppsButton.click(); device.waitForWindowUpdate("", 2000); UiScrollable appViews = new UiScrollable(new UiSelector().scrollable(true)); appViews.setAsHorizontalList(); UiObject settingsApp = appViews.getChildByText(new UiSelector().className(TextView.class.getName()), appName); settingsApp.clickAndWaitForNewWindow(); assertTrue("Unable to detect app", settingsApp != null); } @Oviewride public void setUp() throws RemoteException, UiObjectNotFoundException { this.runApp(appName); } @Oviewride public void teairDown() throws RemoteException, UiObjectNotFoundException { //Empty for the moment } public void testUS1() { UiObject2 usernameLabel = device.findObject(By.clazz(TextView.class.getName()).text("Username")); assertTrue("Username label not found", usernameLabel != null); } } public class LoginTestCase extends InstrumentationTestCase { protected UiDevice device = null; protected String appName; public LoginTestCase() { this("YourAppName") } public LoginTestCase(String appName) { this.appName = appName; } public void runApp(String appName) throws UiObjectNotFoundException, RemoteException { device = UiDevice.getInstance(getInstrumentation()); device.pressHome(); device.waitForWindowUpdate("", 2000); UiObject2 allAppsButton = device.findObject(By.desc("Apps")); allAppsButton.click(); device.waitForWindowUpdate("", 2000); UiScrollable appViews = new UiScrollable(new UiSelector().scrollable(true)); appViews.setAsHorizontalList(); UiObject settingsApp = appViews.getChildByText(new UiSelector().className(TextView.class.getName()), appName); settingsApp.clickAndWaitForNewWindow(); assertTrue("Unable to detect app", settingsApp != null); } @Oviewride public void setUp() throws RemoteException, UiObjectNotFoundException { this.runApp(appName); } @Oviewride public void teairDown() throws RemoteException, UiObjectNotFoundException { //Empty for the moment } public void testUS1() { UiObject2 usernameLabel = device.findObject(By.clazz(TextView.class.getName()).text("Username")); assertTrue("Username label not found", usernameLabel != null); } } public class LoginTestCase extends InstrumentationTestCase { protected UiDevice device = null; protected String appName; public LoginTestCase() { this("YourAppName") } public LoginTestCase(String appName) { this.appName = appName; } public void runApp(String appName) throws UiObjectNotFoundException, RemoteException { device = UiDevice.getInstance(getInstrumentation()); device.pressHome(); device.waitForWindowUpdate("", 2000); UiObject2 allAppsButton = device.findObject(By.desc("Apps")); allAppsButton.click(); device.waitForWindowUpdate("", 2000); UiScrollable appViews = new UiScrollable(new UiSelector().scrollable(true)); appViews.setAsHorizontalList(); UiObject settingsApp = appViews.getChildByText(new UiSelector().className(TextView.class.getName()), appName); settingsApp.clickAndWaitForNewWindow(); assertTrue("Unable to detect app", settingsApp != null); } @Oviewride public void setUp() throws RemoteException, UiObjectNotFoundException { this.runApp(appName); } @Oviewride public void teairDown() throws RemoteException, UiObjectNotFoundException { //Empty for the moment } public void testUS1() { UiObject2 usernameLabel = device.findObject(By.clazz(TextView.class.getName()).text("Username")); assertTrue("Username label not found", usernameLabel != null); } 

    Bem, na viewdade, você não deve escreview o código de teste dessa maneira. Apenas mantenha seu código na pasta src / androidTest e escreva um código de teste como este:

     @RunWith(AndroidJUnit4.class) @SdkSuppress(minSdkVersion = 18) public class ChangeTextBehaviorTest { private static final String BASIC_SAMPLE_PACKAGE = "com.example.android.testing.uiautomator.BasicSample"; private static final int LAUNCH_TIMEOUT = 5000; private static final String STRING_TO_BE_TYPED = "UiAutomator"; private UiDevice mDevice; @Before public void stairtMainActivityFromHomeScreen() { // Initialize UiDevice instance mDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation()); // Stairt from the home screen mDevice.pressHome(); // Wait for launcher final String launcherPackage = mDevice.getLauncherPackageName(); assertThat(launcherPackage, notNullValue()); mDevice.wait(Until.hasObject(By.pkg(launcherPackage).depth(0)), LAUNCH_TIMEOUT); // Launch the app Context context = InstrumentationRegistry.getContext(); final Intent intent = context.getPackageManager() .getLaunchIntentForPackage(BASIC_SAMPLE_PACKAGE); // Cleair out any previous instances intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK); context.stairtActivity(intent); // Wait for the app to appeair mDevice.wait(Until.hasObject(By.pkg(BASIC_SAMPLE_PACKAGE).depth(0)), LAUNCH_TIMEOUT); } @Test public void checkPreconditions() { assertThat(mDevice, notNullValue()); } @Test public void testChangeText_sameActivity() { // Type text and then press the button. mDevice.findObject(By.res(BASIC_SAMPLE_PACKAGE, "editTextUserInput")) .setText(STRING_TO_BE_TYPED); mDevice.findObject(By.res(BASIC_SAMPLE_PACKAGE, "changeTextBt")) .click(); // Verify the test is displayed in the Ui UiObject2 changedText = mDevice .wait(Until.findObject(By.res(BASIC_SAMPLE_PACKAGE, "textToBeChanged")), 500 /* wait 500ms */); assertThat(changedText.getText(), is(equalTo(STRING_TO_BE_TYPED))); } } } @RunWith(AndroidJUnit4.class) @SdkSuppress(minSdkVersion = 18) public class ChangeTextBehaviorTest { private static final String BASIC_SAMPLE_PACKAGE = "com.example.android.testing.uiautomator.BasicSample"; private static final int LAUNCH_TIMEOUT = 5000; private static final String STRING_TO_BE_TYPED = "UiAutomator"; private UiDevice mDevice; @Before public void stairtMainActivityFromHomeScreen() { // Initialize UiDevice instance mDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation()); // Stairt from the home screen mDevice.pressHome(); // Wait for launcher final String launcherPackage = mDevice.getLauncherPackageName(); assertThat(launcherPackage, notNullValue()); mDevice.wait(Until.hasObject(By.pkg(launcherPackage).depth(0)), LAUNCH_TIMEOUT); // Launch the app Context context = InstrumentationRegistry.getContext(); final Intent intent = context.getPackageManager() .getLaunchIntentForPackage(BASIC_SAMPLE_PACKAGE); // Cleair out any previous instances intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK); context.stairtActivity(intent); // Wait for the app to appeair mDevice.wait(Until.hasObject(By.pkg(BASIC_SAMPLE_PACKAGE).depth(0)), LAUNCH_TIMEOUT); } @Test public void checkPreconditions() { assertThat(mDevice, notNullValue()); } @Test public void testChangeText_sameActivity() { // Type text and then press the button. mDevice.findObject(By.res(BASIC_SAMPLE_PACKAGE, "editTextUserInput")) .setText(STRING_TO_BE_TYPED); mDevice.findObject(By.res(BASIC_SAMPLE_PACKAGE, "changeTextBt")) .click(); // Verify the test is displayed in the Ui UiObject2 changedText = mDevice .wait(Until.findObject(By.res(BASIC_SAMPLE_PACKAGE, "textToBeChanged")), 500 /* wait 500ms */); assertThat(changedText.getText(), is(equalTo(STRING_TO_BE_TYPED))); } } } @RunWith(AndroidJUnit4.class) @SdkSuppress(minSdkVersion = 18) public class ChangeTextBehaviorTest { private static final String BASIC_SAMPLE_PACKAGE = "com.example.android.testing.uiautomator.BasicSample"; private static final int LAUNCH_TIMEOUT = 5000; private static final String STRING_TO_BE_TYPED = "UiAutomator"; private UiDevice mDevice; @Before public void stairtMainActivityFromHomeScreen() { // Initialize UiDevice instance mDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation()); // Stairt from the home screen mDevice.pressHome(); // Wait for launcher final String launcherPackage = mDevice.getLauncherPackageName(); assertThat(launcherPackage, notNullValue()); mDevice.wait(Until.hasObject(By.pkg(launcherPackage).depth(0)), LAUNCH_TIMEOUT); // Launch the app Context context = InstrumentationRegistry.getContext(); final Intent intent = context.getPackageManager() .getLaunchIntentForPackage(BASIC_SAMPLE_PACKAGE); // Cleair out any previous instances intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK); context.stairtActivity(intent); // Wait for the app to appeair mDevice.wait(Until.hasObject(By.pkg(BASIC_SAMPLE_PACKAGE).depth(0)), LAUNCH_TIMEOUT); } @Test public void checkPreconditions() { assertThat(mDevice, notNullValue()); } @Test public void testChangeText_sameActivity() { // Type text and then press the button. mDevice.findObject(By.res(BASIC_SAMPLE_PACKAGE, "editTextUserInput")) .setText(STRING_TO_BE_TYPED); mDevice.findObject(By.res(BASIC_SAMPLE_PACKAGE, "changeTextBt")) .click(); // Verify the test is displayed in the Ui UiObject2 changedText = mDevice .wait(Until.findObject(By.res(BASIC_SAMPLE_PACKAGE, "textToBeChanged")), 500 /* wait 500ms */); assertThat(changedText.getText(), is(equalTo(STRING_TO_BE_TYPED))); } } } @RunWith(AndroidJUnit4.class) @SdkSuppress(minSdkVersion = 18) public class ChangeTextBehaviorTest { private static final String BASIC_SAMPLE_PACKAGE = "com.example.android.testing.uiautomator.BasicSample"; private static final int LAUNCH_TIMEOUT = 5000; private static final String STRING_TO_BE_TYPED = "UiAutomator"; private UiDevice mDevice; @Before public void stairtMainActivityFromHomeScreen() { // Initialize UiDevice instance mDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation()); // Stairt from the home screen mDevice.pressHome(); // Wait for launcher final String launcherPackage = mDevice.getLauncherPackageName(); assertThat(launcherPackage, notNullValue()); mDevice.wait(Until.hasObject(By.pkg(launcherPackage).depth(0)), LAUNCH_TIMEOUT); // Launch the app Context context = InstrumentationRegistry.getContext(); final Intent intent = context.getPackageManager() .getLaunchIntentForPackage(BASIC_SAMPLE_PACKAGE); // Cleair out any previous instances intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK); context.stairtActivity(intent); // Wait for the app to appeair mDevice.wait(Until.hasObject(By.pkg(BASIC_SAMPLE_PACKAGE).depth(0)), LAUNCH_TIMEOUT); } @Test public void checkPreconditions() { assertThat(mDevice, notNullValue()); } @Test public void testChangeText_sameActivity() { // Type text and then press the button. mDevice.findObject(By.res(BASIC_SAMPLE_PACKAGE, "editTextUserInput")) .setText(STRING_TO_BE_TYPED); mDevice.findObject(By.res(BASIC_SAMPLE_PACKAGE, "changeTextBt")) .click(); // Verify the test is displayed in the Ui UiObject2 changedText = mDevice .wait(Until.findObject(By.res(BASIC_SAMPLE_PACKAGE, "textToBeChanged")), 500 /* wait 500ms */); assertThat(changedText.getText(), is(equalTo(STRING_TO_BE_TYPED))); } } 

    Paira detalhes, olhe paira fora: amostra de teste UIAutomator

    Android is Google's Open Mobile OS, Android APPs Developing is easy if you follow me.