How to include an excluded source file for tests?

228 views Asked by At

I have a initial data class which should be excluded in the normal (default profile) build. If I specify for example the run profile this class should be included. Furthermore this class is needed by the tests. So it needs to be included all the tim.

I used the excludes to achieve the first part, but the dependency from the test breaks the testCompile goal.

<plugin>
    <artifactId>maven-compiler-plugin</artifactId>
    <executions>
        <execution>
            <id>default-compile</id>
            <goals>
                <goal>compile</goal>
            </goals>
            <configuration>
                <excludes>
                    <exclude>**/InitialDataBuilder.java</exclude>
                </excludes>
            </configuration>
        </execution>
        <execution>
            <id>default-testCompile</id>
            <goals>
                <goal>testCompile</goal>
            </goals>
            <configuration>
                <testIncludes>
                    <include>**/*.java</include>
                </testIncludes>
            </configuration>
        </execution>
    </executions>
</plugin>

What is wrong with my config?
Is there no way to include an excluded source file for tests?

1

There are 1 answers

0
Jon On

Maven's directory structure allows you to easily separate source/production code and test code.

The details of how to layout a project are explained here: https://maven.apache.org/guides/introduction/introduction-to-the-standard-directory-layout.html

Basically, you put your production code in:

src/main/java

Test code goes in:

src/test/java

The test code tree should include the actual unit tests themselves and supporting classes. So the code you described belongs there. It will only end up in the test jar, not the production jar.

Also if you do it this way, you don't need to mess with the compiler plugin settings. The defaults will do what you expect.

Oh one other thing I should mention is that if it is needed for another profile, you should likely make it it's own maven module with it's own POM file. Then this class can reference it as a <scope>test</scope> dependency and the other as a production dependency.