How to include test classes into shadowJar?
Asked Answered
B

2

10

I am using shadow Gradle plugin to build JAR, containing all referenced jars inside.

In my build.gradle I have only

apply plugin: "com.github.johnrengelman.shadow"

and

jar {
    manifest {
        attributes 'Main-Class': 'MYCLASS'
    }

}

related to that. I don't know, how it knows, what to build, but it works.

Now, is it possible, to include test classes too?

Barrel answered 30/11, 2016 at 19:56 Comment(1)
Did you come up with any solution on this one?Natalya
T
4

From the official documentation https://imperceptiblethoughts.com/shadow/custom-tasks/

Shadowing Test Sources and Dependencies

import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar task testJar(type: ShadowJar) { classifier = 'tests' from sourceSets.test.output configurations = [project.configurations.testRuntime] }

The code snippet above will geneated a shadowed JAR contain both the main and test sources as well as all runtime and testRuntime dependencies. The file is output to build/libs/--tests.jar.

Tabasco answered 1/1, 2018 at 14:36 Comment(4)
Unfortunately, the JAR is empty for me. There are neither dependencies nor source classes in it.Gadwall
Doesn't work for me either. Running the jar just outputs Error: Could not find or load main class org.scalatest.tools.Runner. Btw I have dependencies { testRuntime "org.scalatest:scalatest_${scalaBinaryVersion}:3.0.5" }.Milestone
@Milestone seeing that these are the official instructions on how to accomplish the task, I would advise you to visit the plugin's github page and open an issue there if necessary.Tabasco
My tests get included but these won't include the main sources.Turnbull
N
4

The official documentation seems out of date with the latest (v7.0.0) version of the plugin. Using this version and the latest version of gradle (7.0), I do this:

task testJar(type: com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar) {
    archiveClassifier.set("alltests")
    from sourceSets.main.output, sourceSets.test.output
    configurations = [project.configurations.testRuntimeClasspath]
}

The docs have both the from clause and the "configurations" clause wrong.

  • as a comment on the other answer mentions, the main classes (whihc are normally your classes under test) are missing from the jar, so you need to add sourceSets.main.output
  • the project.configurations.testRuntime doesn't work as documented, it tells me testImplementation' is not allowed as it is defined as 'canBeResolved=false
Nelan answered 16/5, 2021 at 9:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.