Gradle test task does not run JUnit test with @Cat

2019-07-02 00:06发布

问题:

Gradle does not run my JUnit test with @Category and @RunWith annotations.

Java 8, Gradle 4.2.1.

My JUnit class:

public interface FastTest {
}

@Category(FastTest.class)
@RunWith(PowerMockRunner.class)
public class MyTest {
    @Test
    public void testMyMethod() {
        // Test method should fail
        assertTrue(false);
    }
}

My build.gradle:

apply plugin: 'java'

repositories { mavenCentral() }

dependencies {
    compile "junit:junit:4.12"
    compile "org.powermock:powermock-core:1.6.5"
    compile "org.powermock:powermock-api-mockito-common:1.6.5"
    compile "org.powermock:powermock-module-junit4:1.6.5"
    compile "org.powermock:powermock-api-mockito:1.6.5"
}

test {
    scanForTestClasses = false

    useJUnit { includeCategories 'FastTest'  }
}

If I remove RunWith annotation, Gradle runs the test. The scanForTestClasses = false setting has no effect.

回答1:

Reported Gradle issue: https://github.com/gradle/gradle/issues/3189.

PowerMock replaces Category annotation with a proxy: RunWith(PowerMockRunner.class) does not work with package annotation

Workaround: Add PowerMockIgnore annotation to JUnit class:

@PowerMockIgnore({ "org.junit.experimental.categories.Category", "mypackage.FastTest" })
@Category(FastTest.class)
@RunWith(PowerMockRunner.class)
public class MyTest {
    @Test
    public void testMyMethod() {
        // Test method should fail
        assertTrue(false);
    }
}