9

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?

Dims
  • 47,675
  • 117
  • 331
  • 600

2 Answers2

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.

Peter Butkovic
  • 11,143
  • 10
  • 57
  • 81
Eyal Roth
  • 3,895
  • 6
  • 34
  • 45
  • Unfortunately, the JAR is empty for me. There are neither dependencies nor source classes in it. – Harold L. Brown May 15 '20 at 19:30
  • 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" }`. – jirislav Jul 23 '20 at 14:23
  • @jirislav seeing that these are the official instructions on how to accomplish the task, I would advise you to visit the [plugin's github page](https://github.com/johnrengelman/shadow) and open an issue there if necessary. – Eyal Roth Jul 31 '20 at 11:27
  • 1
    My tests get included but these won't include the main sources. – dtc Nov 03 '20 at 21:22
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
haelix
  • 4,245
  • 4
  • 34
  • 56