Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Boot useTestClasspath throws CannotLoadBeanClassException and ClassNotFoundException

I have a maven project with a test class located at src/test/java/MyDevClass which is intended for development/testing purposes only. I would like to use it when I start spring-boot-maven-plugin with the command line mvn spring-boot:run.

So, my pom.xml contains:

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>
                <!-- TODO: Will create a maven profile and have useTestClasspath only for development/testing -->
                <useTestClasspath>true</useTestClasspath>
            </configuration>
        </plugin>
    </plugins>
</build>

But, I get the following error:

org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [MyDevClass]
Caused by: java.lang.ClassNotFoundException: MyDevClass

Intriguing enough, I have another project using tomcat7-maven-plugin and it works fine:

        <plugin>
            <groupId>org.apache.tomcat.maven</groupId>
            <artifactId>tomcat7-maven-plugin</artifactId>
            <version>2.0</version>
            <configuration>
                <useTestClasspath>true</useTestClasspath>
            </configuration>
        </plugin>

What I am missing?

like image 516
Rafa Avatar asked Oct 18 '22 00:10

Rafa


1 Answers

Spring-boot maven plugin does not include current module's test sources (and resources) into classpath even if useTestClasspath is set to true.

I ran a forked execution with verbose logging (-X flag to Maven), and the plugin listed the forked JVM classpath. Test classes were not included.

If you look at the plugin sources (version 1.5.3 at time of writing), the flag useTestClasspath is only used in the addDependencies method.

I see two options as workarounds

  1. Add the target/test-classes dir to the run classpath:

    <directories>
      <directory>${project.build.testOutputDirectory}</directory>
    </directories>
    

    For older plugin version use:

    <folders>
      <folder>${project.build.testOutputDirectory}</folder>
    </folders>
    

    The problem here is that the folder is added to the beginning of classpath, while test files are preferable at its end.

  2. Create another Maven module with test classes and resources, and add it as a <scope>test</scope> dependency.

like image 134
leonid Avatar answered Oct 21 '22 04:10

leonid