2

I am testing a delegate class with Junit. When i right click on Run Configurations and put the key-value pair in Environment tab, it works fine.

I unsuccessfully tried to set it from a static block as well as @Before method. Can you help?

public MyClass{
public void myMethod(){
String tmp = configProps.getProperty("auto_commit_location");
String commitScriptLocation = System.getenv(tmp);
System.out.println(commitScriptLocation); --- This returns null
 }
}

Junit Test:

public class AutoCommitControlDelegateTest {

    static {
        System.setProperty("auto_commit_location", "/tmp/");
    }

    @Autowired
    private *******
    //calls to my methods
user892871
  • 1,025
  • 3
  • 13
  • 28
  • Can you share some code? It's easier to help with a concrete problem in front of you... – Mureinik Aug 16 '14 at 10:10
  • What i am trying to do is set an env variable from Junit that will be used inside java class. I looked at the answer. But it doesnt work. – user892871 Aug 16 '14 at 10:12
  • When is the line `String commitScriptLocation = System.getenv(tmp);` called? is it in a static block? a constructor? some other method? – Mureinik Aug 16 '14 at 10:18
  • It gets called from a non-static method. – user892871 Aug 16 '14 at 10:20
  • Are you using eclipse? You could try setting up an ant task which sets environment variables and then runs your junit code. Env variable are read only so you either need to set them outside java or do something like in the the question linked by Emil H. – Salix alba Aug 16 '14 at 10:23

2 Answers2

6

Hmmmm,

I changed this line:

String commitScriptLocation = System.getenv(tmp);

to this:

String commitScriptLocation = System.getProperty(tmp);

and it works . :( I lost 2 hours figuring this out.

kryger
  • 12,906
  • 8
  • 44
  • 65
user892871
  • 1,025
  • 3
  • 13
  • 28
2

To answer your specific question, setting an environment variable in a running JVM is complicated (although possible: Is it possible to set an environment variable at runtime from Java?).

If, instead, you're able to use system properties (What's the difference between a System property and environment variable), then consider using System Rules ("provides an arbitrary value for a system property to a test. After the test the original value is restored."):

public void MyTest {
    @Rule
    public final ProvideSystemProperty myPropertyHasMyValue
     = new ProvideSystemProperty("MyProperty", "MyValue");

    @Test
    public void overrideProperty() {
        assertEquals("MyValue", System.getProperty("MyProperty"));
    }
}
Community
  • 1
  • 1
Joe
  • 29,416
  • 12
  • 68
  • 88