Running a specific instrumentation unit test with Gradle

Solution 1:

Using test.single appears to be deprecated. The new correct way to do this is

./gradlew :<module>:test --tests <pattern>

where <pattern> could be something like:

  • com.example.MyTest to run all test methods in com.example.MyTest
  • *MyTest to match every method in every class whose name ends with MyTest
  • *.MyTest.myMethod to run a specific test method in class MyTest in any package

If you have a multi-project build, make sure to give the module path before the test task; otherwise you'll get a misleading error message when it searches for your test pattern in every subproject.

None of this is documented on the Gradle site anywhere I could find it.

Solution 2:

This works if you're using an instrumentationTestRunner:

./gradlew test -Pandroid.testInstrumentationRunnerArguments.class=<pkg>.YourClassName

Using gradle 2.10 and android gradle plugin 2.0.0-beta2.

Since you know what test(s) you want to run, you probably know which module / flavor to use too. You can help Gradle out by specifying the exact module and Gradle task. So if your test is in the app module and you want to test the debug flavor:

./gradlew app:connectedDebugAndroidTest -Pandroid.testInstrumentationRunnerArguments.class=<pkg>.YourClassName

You can get even more fancy with the tests_regex argument instead:

./gradlew app:connectedDebugAndroidTest -Pandroid.testInstrumentationRunnerArguments.tests_regex=PartialClassName*
./gradlew app:connectedDebugAndroidTest -Pandroid.testInstrumentationRunnerArguments.tests_regex=partialMethodName*