Publishing artifact only after tests were successful

Viewed 22

I've been fighting this problem for a long time and genuinely out of ideas. In my project I use the maven-publish plugin for publishing artifact to my repository:

plugins {
    kotlin("jvm") version "1.6.20"
    id("maven-publish")
}

And also using Kotest to run tests:

tasks.withType<Test> {
    useJUnitPlatform()
}

Obviously, I want to publish artifacts only if all tests passed, so I add the following:

tasks.publish {
    dependsOn(tasks.test)
    mustRunAfter(tasks.test)
}

However, when I run ./gradlew clean build test publish on the command line, the artifacts are always published before the tests run:

> Task :clean
> Task :processResources NO-SOURCE
> Task :processTestResources
> Task :generatePomFileFor«project-name»Publication
> Task :compileKotlin
> Task :compileJava NO-SOURCE
> Task :classes UP-TO-DATE
> Task :inspectClassesForKotlinIC
> Task :jar
> Task :assemble
> Task :generateMetadataFileFor«project-name»Publication
> Task :publish«project-name»PublicationTo«repository-name»Repository
> Task :compileTestKotlin
> Task :compileTestJava NO-SOURCE
> Task :testClasses
> Task :test

Is there something I'm missing?

1 Answers

Took me long enough. Apparently, the publish task is not the one that actually publishes the jar, but the publish«project-name»PublicationTo«repository-name»Repository. However, this task is not available until after configuration, so the best I could do is:

afterEvaluate {
  tasks.getByName("publish«project-name»PublicationTo«repository-name»Repository").dependsOn(tasks.test)
}
Related