3

My team is using JUnit to launch tests from eclipse.

Before executing these tests from eclipse, we have to specify the env variable LD_LIBRARY_PATH to load dependencies at run time. The correct value of LD_LIBRARY_PATH can change when one of my team's member commits a change in the project. We have a script which computes its correct value.

Today, we have two solutions to set the variable :

  • run the script to get the value, and for each JUnit test we want to run, set it in Run Configurations window.
  • write a script which sets the variable and launches eclipse.

First method is unproductive, and with second method, we have to restart eclipse each time we update the project.

A better solution would be to write a script which would set the variable and which would be called by eclipse each time a test is run.

Is there a way to call a script before each test with Eclipse ? Any other idea would be also greatly appreciated.

gloups
  • 31
  • 1
  • 2

1 Answers1

3

Following the idea of the SO queston How to run Unix shell script from Java code? you could execute a script before each test or each test class as follows

@Before // could also be @BeforeClass
public void setupEnvViaScript() throws IOException, InterruptedException {
  ProcessBuilder processBuilder = new ProcessBuilder("my-script.cmd", "arg-1", "arg-2");
  processBuilder.environment().put("JAVA_HOME", "value");
  processBuilder.environment().put("ENV_VAR", "value");

  processBuilder.directory(new File("d:/working/path/script/shall/be/executed/in"));
  Process process = processBuilder.start();

  int exitValue = process.waitFor();
  if (exitValue != 0) {
    // check for errors
    new BufferedInputStream(process.getErrorStream());
    throw new RuntimeException("execution of script failed!");
  }
}

This has some caveats

  • this way it is platform depended
  • the script and the path to it are hard-coded
  • the working-directory is hard-coded

You could tackle this in several ways, like

  • generate the script file on the fly before execution
  • choose the execution path depended from some constraints
Community
  • 1
  • 1
cheffe
  • 9,345
  • 2
  • 46
  • 57
  • Wouldn't that simply start a separate process independent of the process running the junit? So that the separate process would not be able to affect the env of the junit process. – Blessed Geek Jun 17 '20 at 21:37