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 
5
  • Can you share some code? It's easier to help with a concrete problem in front of you... Commented Aug 16, 2014 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. Commented Aug 16, 2014 at 10:12
  • When is the line String commitScriptLocation = System.getenv(tmp); called? is it in a static block? a constructor? some other method? Commented Aug 16, 2014 at 10:18
  • It gets called from a non-static method. Commented Aug 16, 2014 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. Commented Aug 16, 2014 at 10:23

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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")); } } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.