简体   繁体   中英

How to reuse classes from /src/test/java in different project?

I have a class in a commons library that I placed into /src/test/java . Then I want to reuse that class in any project having the commons library as dependency.

But the file cannot be imported.

Common custom library:

/src/test/java/com/myproject/utils/TestfileReader.java

Implementation project:

<dependencies>
    <dependency>
        <groupId>com.myproject</groupId>
        <artifactId>my-commons</artifactId>
        <version>1.0.0</version>
    </dependency>

usage:

/src/test/java/com/myproject/itest/SomeTest.java

import com.myproject.utils.TestfileReader;

Result: the import cannot be resolved.

But if I copy that file to /src/main/java/... it can be found correctly. So my commons library seems to be fine in general.

Question: how can I make this file visible only to my tests, while keeping it in /src/test/java folder?

you can do this by specifying the type to test-jarscope.

<dependency>
    <groupId>com.myproject</groupId>
    <artifactId>my-commons</artifactId>
    <version>1.0.0</version>
    <type>test-jar</type>
    <scope>test</scope>
</dependency>

You can control whether your resources under your src/test folder will get shipped or not, eg via the maven-resource-plugin See here: http://maven.apache.org/plugins/maven-resources-plugin/testResources-mojo.html

An example here would copy all sources found under src/test/java into your final build.

<testResources>
  <testResource>
    <directory>${project.basedir}/src/test/java</directory>
  </testResource>
</testResources>

You may do the following:

  • Create a jar file from the project that you want to share in different projects.
  • Use this jar file as dependencies by giving group id, artifact id and version.
  • Remember to add index of this jar file in your external dependencies.

Absolutely, one can do it..

First You need to navigate to Build Path-->Configure Build Path--> Source tab

then in the Source tab search/check [your Project Name]/src/main/java and change

"contains test sources" from No to Yes and save it.

This will resolved issue of import packages from "src/test/java" to "src/main/java" successfully

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