Explain Codes LogoExplain Codes Logo

Sharing src/test classes between modules in a multi-module maven project

java
test-jar
modular-builds
reusability
Anton ShumikhinbyAnton Shumikhin·Dec 6, 2024
TLDR

Make your life easier. Jam-pack src/test classes into a test-jar using the reliable maven-jar-plugin. Then drag-and-drop this attribute as a test-scoped dependency in the module that’s itching for these classes:

Module-that-makes pom.xml: // This module makes things. Like a robot assembly line!

<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <executions> <execution> <goals><goal>test-jar</goal></goals> <!-- Remember: Life's full of goals, find yours! --> </execution> </executions> </plugin>

Module-that-takes pom.xml: // Does it give back, though? 🤔

<dependency> <groupId>your.group.id</groupId> <artifactId>module-that-makes</artifactId> <version>your.version</version> <type>test-jar</type> <scope>test</scope> </dependency>

There you have it: method to the madness of reusing test code! 🎉

Streamline the build sequence

In an ideal world, your projects depending on shared test artifacts should pine to build in perfect pecking order. Maven's almighty reactor's got your back if you pen down your modules in your parent POM correctly. If not, brace yourself for build errors barking about a missing test JAR. Who let the dogs out, right?

Outsmart cyclic dependencies

When sharing your precious test code, beware of those vicious circular dependencies. They can muddle up your build order and blur the lines of module separation. By showcasing your test artifacts distinctively and adhering to a producer-consumer balance, your project stays in its Sunday best - modular and maintainable.

Preserve test scope with gusto

Don’t let your src/main and src/test separation feel left out. By cosying up with a test-jar, your test classes and VIP utilities like SampleDataHelper, are segregated from production code, just as nature intended. Clean, green production artifacts, coming up!

More cool stuff with test JARs in modular builds

Slap together more complex scenarios with modular builds using this strategy and unscramble your test-code dependencies from module-to-module dependencies. Sounds spicy, right?

Talk the reusable test design language

Train your sights on reusability for your tests. This mindset switch paves the way for shared tests to feel right at home, just like production code.

Designing test standards for complex scenarios

Caught in a place where one module's tests are skyrocketing into de-facto standards? Here's your cue to use the test-jar route. It lets standardizing practices come naturally without forcing them, incentivizing good practices across team lines.