androidunit-testingandroid-gradle-pluginadbinstrumented-test

Run instrumented test with Gradle while skipping build and installation


Is there a way to run instrumented test with Android Gradle Plugin without running a build task and installation task? I need to do the installation of test APKs via adb for a very specific reason, however if I do the instrumentation with adb shell am instrument -w it doesn't generate test report like the one from ./gradlew cAT.

Installation via ADB

adb install app/build/outputs/apk/debug/app-debug.apk & adb install app/build/outputs/apk/androidTest/debug/app-debug-androidTest.apk    

If my understanding is correct ./gradlew cAT or ./gradlew connectedAndroidTest will build and install APK. I only need to run the tests and get its HTML report, it will be a waste of build minute in CI pipeline to include build and install task while it is already done via ADB.


Solution

  • As you mentioned, AGP's connectedAndroidTest task builds and installs all the apks that are needed to execute the instrumented test(s).

    The code isn't structured in a way that you can execute in isolation only the final task that runs the tests and builds the html report because there is a dependency with the assembleTask both for the app and the test apks: you can see it from here.

    I had a similar requirement in the past and what I did is to use a custom test listener that intercepts when the tests fails/passes and collects the results in junit xml format. You can then convert it to html with some other tools.

    The listener I used can be specified in the build.gradle file

    android {
       defaultConfig {
           ...
           testInstrumentationRunnerArgument "listener", "de.schroepf.androidxmlrunlistener.XmlRunListener"
       }
    }
    

    or via adb by adding the following parameter when you execute the instrumented tests:

    -e listener de.schroepf.androidxmlrunlistener.XmlRunListener
    

    The listener referencef above is no longer available in jcenter therefore you have to add it as source code into your project (respecting the license the author selected, if any).

    Hope this helps