android – Running gradle's connectedAndroidTest on a specific device-ThrowExceptions

Exception or error:

How do you run connectedAndroidTest on a particular device?

I would expect something like:

./gradlew connectedAndroidTest -DconnectedAndroidTest.device=XXXX

We have a number of devices plugged into our CI server and I can’t seem to find any documentation on how to target a specific connected device.

connectedAndroidTest runs the tests on ALL connected devices currently.


How to solve:

Use the ANDROID_SERIAL variable

You can do this two ways:

1. Set environment variable

# Set once; all following gradlew commands will use this
export ANDROID_SERIAL=1000AB0123456YZ

./gradlew <...>

2. “Set” for just a command

ANDROID_SERIAL=1000AB0123456YZ ./gradlew <...>

If you set/exported ANDROID_SERIAL (method #1), you can use this to override that for a single command.


This works with emulator identifiers (e.g., “emulator-5554”), too.


It’s not supported. The documentation for connectedCheck at, which delegates to connectedAndroidTest for these sorts of on-device non-UI-automated tests, explicitly states:

Runs checks that requires a connected device or
emulator. They will run on all connected devices in parallel.

There is a feature request for the ability to select individual devices; you can track its progress at


I created an “hack” to be able to do it.. put this block in the android section of your build.gradle, and then you have to set the ANDROID_HOME env variable to the sdk folder, and the UNIT_TESTS_DEVICE_ID env variable with the serial number of the device on which you want to run tests on.

deviceProvider(new"ANDROID_HOME") + File.separator + "platform-tools" + File.separator + "adb")) {
    public String getName() {
        return "singleDevice"

    public List<? extends> getDevices() {
        List<> devices = super.devices;
        List<> toReturn = new ArrayList<>();
        String deviceSerialNum = System.getenv("UNIT_TESTS_DEVICE_ID");
        devices.each {
            if (it.getSerialNumber().equals(deviceSerialNum)) toReturn.add(it);
        if (toReturn.isEmpty()) {
            throw new RuntimeException("Device for unit tests not found!");
        return toReturn;

Then you use the task singleDeviceAndroidTest{Variant} to run the tests. Tested only on gradle plugin version 1.0.0.


It should be possible now. Just set ANDROID_SERIAL environment variable to the device id you want your tests to run on.

Leave a Reply

Your email address will not be published. Required fields are marked *