4

I am trying to use ProcessBuilder to start a JUnit test within my Java Application.

I am able to run the same command from the command line without issue. Do I need to use the absolute path for the jar when running from ProcessBuilder or can I use the relative path?

Running on the command line

java -cp .;lib/junit-4.12.jar org.junit.runner.JUnitCore com.test.Test1

Running inside my application

The junit library is in the lib folder

application/lib/junit-4.12.jar

        ProcessBuilder builder = new ProcessBuilder(new String[] {"java", "-cp", ".;lib/junit-4.12.jar", "com.test.Test1"});

        Process process = builder.start();
        process.waitFor();

        debug("process ended");
        debug("process.exitValue() = " + process.exitValue());

Output:

process ended
process.exitValue() = 1
Error: Could not find or load main class org.junit.runner.JUnitCore
ALM
  • 2,555
  • 7
  • 31
  • 45

2 Answers2

2

You can find what the classpath is when you run your application by using System.getProperty("java.class.path"); Then, modify "cp" in your ProcessBuilder() statement accordingly.

mazaneicha
  • 8,794
  • 4
  • 33
  • 52
  • How can I use more than one libarary in my -cp in the `ProcessBuilder` statement it seems to not find it once I have more than one "one.jar;two.jar" will fail but "one.jar" will work. – ALM Jul 22 '16 at 00:44
  • You can use yet another system property `System.getProperty("path.separator");` to find the right separator character. They are OS-dependent. See also other SO posts on the subject: http://stackoverflow.com/questions/4528438/classpath-does-not-work-under-linux – mazaneicha Jul 22 '16 at 11:16
0

Set the base directory for the ProcessBuilder you are wanting to use.

File libDir = new File("/opt/app/lib");
builder.directory(libDir);

This is the solution I ended up using after @mazaneicha 's comment to relook at the app's classpath directory.

ALM
  • 2,555
  • 7
  • 31
  • 45