使用ProcessBuilder API,您可以在启动每个进程之前更改环境变量。这是一个代码片段,您可以如何做到这一点。
@Test
void testVariant1(){
String [] commandArray =
{"java", "-cp", "your/class/path", "org.mydomain.myClass", ...};
Map<String, String> envVarsForThisTest = new HashMap<String, String>();
envVarsForThisTest.put("newProperty", "value1");
List<String> staleVars = new List<String>();
stateVars.add("oldProperty");
File workingDir = new File("myDir"));
Process p = runVariant(
commandArray, envVarsForThisTest, staleVars, workingDir);
Assert.assert(p.waitFor(), 0);
checkAssertions(p.getOutputStream(), p.getErrorStream());
}
void checkAssertions(OutputStream output, InputStream errorStream){
// where you'll check the return values against your expectations
}
void runVariant(String commandArray[],
Map<String,
String> newEnvironmentVariables,
List<String> environemntVariablesToRemove,
File workingDirectory){
ProcessBuilder pb = new ProcessBuilder(commandArray);
Map<String, String> env = pb.environment();
for(Map.Entry<String, String> entry : newEnvironmentVariables){
env.put(entry.key(), entry.value());
}
for(String staleVariable : environemntVariablesToRemove){
env.remove(staleVariable);
}
pb.directory(workingDirectory);
return pb.start();
}