Home > front end >  How can test classes in Maven project access source classes from main folder?
How can test classes in Maven project access source classes from main folder?

Time:07-31

I know that Maven lifecycle has test stage. The convention is to place tests under the same package as the original classes being tested. But how exactly the test classes have access to the original classes, they reside in separate root folders main vs test. Does Maven merge main and test classes somehow so that during the actual test stage the original file resides in the same directory as the test file? For example, if the main folder structure is:

src/main/java/com/example/
|-- A.java

and test folder structure is:

src/test/java/com/example/
|-- ATest.java

does Maven create a temporary folder structure like:

src/main/java/com/example/
|-- A.java
|-- ATest.java

This may sound as a trivial question but I wasn't able to find any details on the inner working Maven on this topic.

CodePudding user response:

Maven doesn't copy the source files but builds the test classpath after the sources are compiled.

Look at the Maven Surefire Plugin documentation, specifically the The Default Classpath section (Configuring the Classpath page) which states:

The Surefire plugin builds the test classpath in the following order:

  1. The test-classes directory
  2. The classes directory
  3. The project dependencies
  4. Additional classpath elements

CodePudding user response:

The Java files from both those folders get compiled to separate subfolders (target/classes and target/test-classes) of the target folder. Then, when running the tests, both of the folders are put on the classpath.

I’ve rewritten a maven build as a shell script once. It might make it clearer for you. https://github.com/Crydust/buildtools/blob/master/shell/build.sh

  • Related