Question

I have similar code to this one (update environment variable):

private static void setEnv(Map<String, String> envs) {
    try {
        Class<?> pec = Class.forName("java.lang.ProcessEnvironment");
        Field tef = pec.getDeclaredField("theEnvironment");
        tef.setAccessible(true);

        Map<String, String> env = (Map<String, String>) tef.get(null);
        env.clear();
        env.putAll(envs);

        Field tcief = pec.getDeclaredField("theCaseInsensitiveEnvironment");
        tcief.setAccessible(true);
        Map<String, String> cienv = (Map<String, String>) tcief.get(null);
        cienv.clear();
        cienv.putAll(envs);
    } catch (Exception e) {
        logger.printStackTrace(e);
    }
}

I've written some unit tests for this code and now I'm testing on Java 8 (1.8.0). This code doesn't work for Run in JUnit, but works when is running as Debug (with and without breakpoints). Doesn't work means I get my environment variable (PATH) like this

String path = System.getenv("PATH");

and I see there is no my path (c:\\temp). Testing on Java 7 (1.7.0_51) works fine, all Javas are 32-bit, I'm using no additional threads. Do you have any ideas how to solve this?

Was it helpful?

Solution

The problem was in the case sensitivity keys. Parameter envs was created as

Map<String, String> envs = new HashMap<String, String>();

but creating it as

Map<String, String> envs = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER);

solved the problem. I got different results for env["Path"], env["PATH"] and so on.

OTHER TIPS

You can also achieve this using System Stubs - https://github.com/webcompere/system-stubs

Map<String, String> someMap = ...; // work out the env variables
EnvironmentVariables environmentVariables = new EnvironmentVariables(someMap);

The environment variables are applied to the environment while the object is active. This is achieved either through its JUnit 4 or 5 plugins, or via using the execute method on the object to wrap around the executable code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top