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?
You can produce a jar which will include your test classes and resources. To reuse this artifact in an other project, you must declare this dependency with type test-jar : <project> ...
Use the command mvn -DskipTests=true package . This will compile all tests but not run them.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With