How to run single Android local unit test using gradle 2.4. Test filtering is not supported

2.2k Views Asked by At

I'm using gradle to build my android project and am not able to run single local unit test. I have several test classes and one of them is MockServerTest and I only want to run test methods in this class.
I tried using gradle -Dtest.single=MockServerTest test but it turned out running all my tests, including these in other test classes.
I also tried gradle test --tests MockServerTest but an error occurred said

Test filtering is not supported for given version of junit. Please upgrade junit version to at least 4.6.

But I'm using junit 4.12 in my gradle file

testCompile 'junit:junit:4.12'

I'm using gradle 2.4 with com.android.tools.build:gradle:1.2.3. Also, how can I run a single test method inside a single test class?

BTW, I'm able to run single test method inside Android Studio, by right clicking on the test method and select run targetTestMethod() from the menu. But how can I achieve this in the terminal? I guess Android Studio also trigger a certain command to do this. How can I see what that command is?

3

There are 3 best solutions below

1
On BEST ANSWER

Figured it out myself. I have to run

gradle testDebug --tests com.my.package.TestClassName

There are two things to note here.
1. You have to use gradle testDebug or gradle testRelease instead of just gradle test. If you have build variant, you have to use gradle testVariantNameDebug or gradle testVariantNameRelease
2. You have to specify the whole qualified class name, means including the package name.

1
On

Have you tried running gradle test -Dtest.single=MockServerTest? More information can be found here.

0
On

You can use Android Gradle plugin DSL to set up test tasks filters like this:

android {
  testOptions {
    unitTests.all {
      it.testNameIncludePattern = "*.SomeTest"
    }
  }
}

You can find more information on testOptions here and filters here.