Question

I have a java console based application that is created as a jar file and is run using:

java -jar commandlineapp.jar

The application is built using maven. I have a junit test project that is also a maven project, i.e.

parent
+- pom.xml
+- commandlineapp
|  +-pom.xml
+- commandlineapp_test
   +pom.xml

The test project has a dependency on the commandlineapp to ensure that the app is built prior to running the test.

The test project has some junit unit tests that execute the commmandlineapp using ProcessBuilder. E.g.

String jarfile = 
 "C:\\Users\\me\\.m2\\repository\\my\\org\\commandlineapp\\0.0.1-SNAPSHOT\\commandlineapp-.0.1-SNAPSHOT.jar";

ProcessBuilder pb = new ProcessBuilder("java", "-jar", jarFile);

At the moment, you can see that I have a hard-coded path to the commandlineapp jar file.

Question: is there some meta data that I can use to look up jar path for the sibling project? Ideally, I would still like to be able to run the unit tests from eclipse in addition to running them from maven.

Was it helpful?

Solution

One way is to use the maven dependency plugin in the test project to copy the commandlineapp (and its dependencies) to the test project:

     <plugin>
        <artifactId>maven-dependency-plugin</artifactId>
        <executions>
           <execution>
              <phase>process-test-resources</phase>
              <goals>
                 <goal>unpack-dependencies</goal>
              </goals>
              <configuration>
                 <outputDirectory>${project.build.directory}/lib</outputDirectory>
              </configuration>
           </execution>
        </executions>
     </plugin>

Then from within the test project, you can get access to the target folder:

File testClassesFolder = 
   new File(CommandLineAppTest.class.getClassLoader().getResource(".").getFile());

We need to create a string with the class path. The classpath

String classPath = testClassesFolder.getParent() + File.separator + "lib";

Then pass this to ProcessBuilder:

ProcessBuilder pb = 
  new ProcessBuilder(
     javaExecutablePath, "-cp", classPath, "my.org.CommandLineApp"
  );
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top