0

I need to use some environment variables in my unit tests. Consider the following test class

public class MyTest 
{

private String myVar=null;

@Before
    public void setUp()
    {
        myVar = System.getEnv("myEnv");
    }

@After
    public void tearDown() {}

@Test
    public void myTestMethod()
    {
        assertNotNull(myVar);
    }
}

now in the eclispe debug/run settings of the MyTest class, i define the environment variable as

myEnv=myVal

and when I run the MyTest class as a jUnit test, the myTestMethod passes.

However, when i try to run myTestMethod as a jUnit test, it gives me a NullPointerException.

The only way to make it pass is to create a new run/debug configuration specifically for myTestMethod and creating the environment variable again in the new configuration.

This is extremely frustrating as I can have dozens of environment variables and tests.

Is there any way to solve this problem in eclipse? I have not worked with intelliJ but does that also suffer from the same problem? Or is it more of a jUnit issue?

AbtPst
  • 7,778
  • 17
  • 91
  • 172

1 Answers1

0

Existing launch configuration are not reused when running a single test method: see Eclipse bug 213316, except in the JUnit view. Perhaps there are plug-ins that implement the behavior you want. Alternatively, you could implement the behavior you want yourself, based on the Eclipse source code.

No solution, but a shortening: Press Ctrl and click on the run button or on a run configuration menu item to open the previous launched or the corresponding launch configuration.

You may also take into consideration to change your code to solve the problem of at runtime unchangeable environment variables:

  • In production code use Env.getenv(...) instead of System.getenv(...):
    public class Env {
        private static Function connector = System::getenv;
        public static void setConnector(Function newConnector) {
            connector = newConnector;
        }
        public static String getenv(String name) {
            return connector.apply(name);
        }
    }
  • In test code set environment variables by redirect Env.getenv(...):
    @Before
    public void setUp() {
        Map env = new HashMap<>();
        env.put("myEnv", "42");
        Env.setConnector(env::get);
        //...
    }
howlger
  • 31,050
  • 11
  • 59
  • 99