Tuesday, April 16, 2013

Adding a SystemEnvironment variable - for unit-tests

I recently came across a situation where I want to test a piece of code which looks for Environment variable and it is not available to during testing. (Especially when the application is launched from spring configuration, and the environment variables are set from application-context.xml.

Use the following piece of code to set the system environmnet variable in memory and do not forget to remove after the test case is successful.


public static void setSytemEnvInMemory(
            String key, String value) throws Exception {
        Map<String, String> env = System.getenv();
        Field field = env.getClass().getDeclaredField("m");
        field.setAccessible(true);
        ((Map<String, String>) field.get(env))
                .put(key, value);
    }

The above code basically uses reflection to get the map that stores the environment variables in System class.

The use of reflection is sometimes limited by SecurityManager, but in most cases this should work seamlessly.

This works well on RHEL.
There is post in stack-overflow for code to work on "Windows"

No comments:

Post a Comment