kotlingradletesting

Gradle Filtering Tests in a package except one


I am trying to filter all tests in a particular folder except one test which I want to run.

I have tried this which does not seem to work

filter {
    // Then exclude all tests in these packages
    excludeTestsMatching("com.abc.foo.spec.package.*")
    
    // Finally include the specific tests again to ensure they run
    includeTestsMatching("com.abc.foo.spec.package.DummyPassingSpec")
}

I have also tried the following regex pattern, but does not seem to work

filter {
    excludeTestsMatching("com.abc.foo.spec.package.(?!DummyPassingSpec).*")
}

Solution

  • I couldn’t find a way to exclude an entire package except for one class using excludeTestsMatching and includeTestsMatching.

    excludeTestsMatching and includeTestsMatching supports only a wildcard * in patterns, so you cannot use negative lookaheads ((?!...)).

    But you can achieve the desired result using Test#exclude(Spec<FileTreeElement> excludeSpec)

    tasks.withType<Test> {
        useJUnitPlatform()
        exclude { elem ->
            val regex = "com/abc/foo/spec/package/(?!DummyPassingSpec).*".toRegex()
            regex.matches(elem.path)
        }
    }
    

    Or if you want to avoid regular expressions in your code, you could use following:

    tasks.withType<Test> {
        useJUnitPlatform()
        exclude { elem ->
            val packageAsDir = "com/abc/foo/spec/package/"
            elem.path.contains(packageAsDir) && !elem.path.contains("$packageAsDir/DummyPassingSpec")
        }
    }