简体   繁体   中英

Add src/main/resources to classpath when running unit test in eclipse for spring

In eclipse my maven project has a 'src/main/resources/' folder and a 'src/test/resources' folder. The contents of both directories seem to go into 'Project/target/classes', and the content of just the 'src/test/resources' directory goes into 'Project/target/test-classes'.

When I use spring to load a classpath resource whilst testing, it seems to only have available the stuff that's in 'test-classes' folder on the classpath. This makes sense, as only testing resources go in the classpath for testing.

However I want my main resources to be available when running unit tests aswell, but they cannot be found when running unit tests as they are not on the classpath. How do I configure my way around this problem?

You can configure the surefire plugin (which is what maven uses to run unit tests) to include any additional classes, jars or resource directories.

http://maven.apache.org/plugins/maven-surefire-plugin/examples/configuring-classpath.html

When using TestNG to test a project that contains MyBatis, an exception may not be found in the XML file

org.apache.ibatis.binding.BindingException: Invalid bound statement (not found):

  1. Assume that the XML files corresponding to your MyBatis are all placed under src/main/resources/mapper
  2. After compilation, the target/classes folder will contain the mapper folder
  3. There is no mapper folder in the target/test-classes folder! So the error is reported

Solution In the pom.xml file, point the Test's resources directory to src/main/resources

    <build>
        <testResources>
            <!--测试的时候直接读取src/main/resources的资源文件-->
            <testResource>
              <directory>${project.basedir}/src/main/resources</directory>
            </testResource>
        </testResources>
    </build>

Chinese description 中文说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM