I have found out that the solution is to create a second AndroidManifest.xml, just for the tests. It has to be saved into the tests directory and needs to contain only the overrideLibrary statement:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="${applicationId}">
<uses-sdk tools:overrideLibrary="android.app, android.support.test, android.support.test.rule, android.support.test.espresso, android.support.test.espresso.idling, android.support.test.uiautomator.v18"/>
</manifest>
If you are using a different directory for your tasks, you can specify it this way in your gradle file:
androidTest.setRoot('src_test_uiautomator')
The AndroidManifest.xml file has to be in the root of that directory, the test sources in the “java” subdirectory.