How to package test classes into the jar without running them?

10,428

Solution 1

if youre following maven conventions then your test classes are under src/test/java. maven never packages the contents of the test sources subdirectory into the artifact.

you have (at least ...) 3 alternativs:

put the tests with the "normal" sources

if you REALLY want them packaged (why?) then you should place the test classes under src/main/java where they will be treated as normal source and their compiled classes packaged into the artifact (usually *.jar)

you imght run into all sorts of issues doing this. for example your artifact will have a compile-scoped dependency on junit, which might interfere with other modules using your jar.

also, you might have to configure the maven plugins running the tests to be aware of your test classes if you do this (that is if you ever do want to run tests as part of your build). for example the surefire and failsafe plugins.

configure the maven jar plugin to build a tests jar

see the maven jar plugin documentation. they even have a section titled "How to create a jar containing test classes" - the instructions there will cause your tests to be packaged into a separate jar file (which is probably a much better idea).

create the jar your way using the assembly plugin directly

yuo could disable the default execution of the jar plugin and instead add an execution of the assembly plugin to the package phase to create a jar. you will need to write an assembly descriptor for this (not as complicated as the above link makes it out to be). this will give yu full control over what get included in the jar produced. its best to start by copying one of the predefined assemblies

Solution 2

If it is tests for the current project, then it should be in src/test/java and it will not be included in the main jar. This is the most common use case. If you are writing a test library that will be used in other projects, put them in src/main/java, and add it as a dependency with test scope in those projects.

If you want to distribute everything in a "self contained package", you can either share the code through a version control repository, or create a source jar with the maven assembly plugin.

Share:
10,428
dcsordas
Author by

dcsordas

Updated on June 10, 2022

Comments

  • dcsordas
    dcsordas almost 2 years

    I'm struggling with including my test classes into the jar package, but not running them. After some googling, I've tried mvn package -DskipTests, but my test classes are simply not added to the jar.

    Any ideas?