JUnit Listener Configuration In Gradle

2020-04-16 05:35发布

问题:

I'm new bee to Gradle. Have custom JUnit Listener, which reads the custom annotation data and generates report and need to configure it as part of Gradle. Is there anyway to configure below surefire plugin in Gradle 4.4.

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.18.1</version>
    <configuration>
        <properties>
            <property>
                <name>listener</name>
                <value>my.company.MyRunListener</value>
            </property>
        </properties>
    </configuration>
</plugin>

I understand that, it may not possible to use maven plugin as is in gradle. I checked TestListener, it doesn't have support to read annotations to proceed with that.

I would like to understand the way to configure my JUnit Listener in Gradle.

回答1:

I’m afraid, there is currently no support for JUnit RunListeners in Gradle. There is only an open ticket requesting that feature: https://github.com/gradle/gradle/issues/1330

As someone has mentioned in the comments on that ticket, “the primary issue […] is the absence of TestDescriptor.getAnnotations()” in Gradle; otherwise you might have been able to rewrite your RunListener as a Gradle TestListener. So unless I’ve missed something when skimming through the ticket, it seems that you are mostly out of luck at the moment :-(



回答2:

The JUnit Foundation library enables you to declare your listeners in a service provider configuration file, which are then attached automatically - regardless of execution environment. Details can be found here.

Gradle Configuration for JUnit Foundation

// build.gradle
...
apply plugin: 'maven'
sourceCompatibility = 1.8
targetCompatibility = 1.8
repositories {
    mavenLocal()
    mavenCentral()
    ...
}
dependencies {
    ...
    compile 'com.nordstrom.tools:junit-foundation:9.1.1'
}
ext {
    junitFoundation = configurations.compile.resolvedConfiguration.resolvedArtifacts.find { it.name == 'junit-foundation' }
}
test.doFirst {
    jvmArgs "-javaagent:${junitFoundation.file}"
}
test {
//  debug true
    // not required, but definitely useful
    testLogging.showStandardStreams = true
}

ServiceLoader provider configuration file

# src/main/resources/META-INF/services/org.junit.runner.notification.RunListener
com.example.MyRunListener

With this configuration, the listener implemented by MyRunListener will be automatically attached to the RunNotifier supplied to the run() method of JUnit runners. This feature eliminates behavioral differences between the various test execution environments like Maven, Gradle, and native IDE test runners.