Maven project - a collaborative project

I'm new to Maven, and I'm trying to convert several projects to work on Maven, and I'm not sure if this is the right way to structure them. Here is what I have:

I have a common module called Common and two different applications that have nothing to do with the fact that both of them depend on Common . Call them A and B

The dependencies between ACommon and BCommon are fulfilled both for runtime and for tests - this means that for classes A for testing Common test classes are required.

I tried various combinations that I could think of, but not of them produced what I want. It is strange that my code compiles, but JUnits fail because the test classes from Common not found in the classpath.

Should I add 2 profiles in Common to create 2 artifacts and add 2 dependencies in A and B to both artifacts? (Is this possible?) Is there a right way to do what I wanted? Should I rebuild my code to match Maven?

+6
source share
3 answers

This is a common trap. Test classes from an artifact are not available if you depend on this artifact. This is really reasonable: when you depend on Common , you depend on production classes (JAR file). Test classes are only needed to run tests and are not even included in the final JAR.

Assuming your Common test classes contain some utility method needed for all Common tests, tests A and B , here is the suggested structure:

  • Common-test - contains general utility test classes (not test examples!) In /src/main/java (!)
  • Common depends on Common-test with <scope>test</scope>
  • A and B depend on both Common (default) and Common-test (with test scope)

UML

+5
source

You can create it as

  • General project
  • Project
  • B project

Now add a CommonProject to the <dependency> for A and B , which will make compilation time available for the general project, so the build will be good,

If your A and B is either a webapp configuration, you need to make sure your dependencies are available in WEB-INF / lib so that it can receive dependencies at runtime

To make dependencies available only in test , you can use the test area

+2
source

You need to run the test-jar target maven-jar-plugin in your Common project.

This creates a new artifact with the classifier tests , which contains all the classes and resources from the src/test tree.

So in Common add this:

 <plugins> ... <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <executions> <execution> <id>test-jar</id> <goals> <goal>test-jar</goal> </goals> </execution> </executions> </plugin> ... </plugins> 

And in A and B add this

 <dependency> <groupId>common.group.id</groupId> <artifactId>Common</artifactId> <version>1.0</version> <classifier>tests</classifier> <scope>test</scope> </dependency> 

Note <classifier>tests</classifier> in this dependency declaration.

+2
source

Source: https://habr.com/ru/post/918781/


All Articles