Java – How to run a single Android native unit test using gradle 2.4. Test filtering is not supported

How to run a single Android native unit test using gradle 2.4. Test filtering is not supported… here is a solution to the problem.

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

I’m building my android project using Gradle, but I can’t run a single native unit test. I have several test classes, one of which is MockServerTest, and I just want to run test methods in this class.
I tried using gradle -Dtest.single=MockServerTest test but ended up running all my tests, including those in other test classes.
I’ve also tried gradle test --tests mockServerTest but an error says

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 use gradle 2.4 in com.android.tools.build:gradle:1.2.3.
Also, How do I run a single test method in a single test class?

By the way, I can run a single test method in Android Studio by right-clicking the test method and selecting run targetTestMethod() from the menu. But how can I achieve this in the terminal? I guess Android Studio would also trigger a command to do this. How can I see what the command is?

Solution

I figured it out myself. I have to run

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

There are two points to note here.
1. You must use gradle testDebug or gradle testRelease instead of just gradle test. If you have build variants, you must use gradle testVariantNameDebug or gradle testVariantNameRelease

2. You must specify the full qualified class name, meaning including the package name.

Related Problems and Solutions