How to Test Code Dependent on Environment Variables Using Junit

How to test code dependent on environment variables using JUnit?

The library System Lambda has a method withEnvironmentVariables for setting environment variables.

import static com.github.stefanbirkner.systemlambda.SystemLambda.*;

public void EnvironmentVariablesTest {
@Test
public void setEnvironmentVariable() {
String value = withEnvironmentVariable("name", "value")
.execute(() -> System.getenv("name"));
assertEquals("value", value);
}
}

For Java 5 to 7 the library System Rules has a JUnit rule called EnvironmentVariables.

import org.junit.contrib.java.lang.system.EnvironmentVariables;

public class EnvironmentVariablesTest {
@Rule
public final EnvironmentVariables environmentVariables
= new EnvironmentVariables();

@Test
public void setEnvironmentVariable() {
environmentVariables.set("name", "value");
assertEquals("value", System.getenv("name"));
}
}

Full disclosure: I'm the author of both libraries.

Overwrite environment variable in Java Lambda function

As Mark pointed out in his comment, my question isn't specific to AWS or Lambda.

If you want to set the value of environment variable specifically for testing, this post explains how to do it: How to test code dependent on environment variables using JUnit?

Test classes dependent on environment variables

Use a fake instead. It can be a better option when the alternative is something hard to mock. In your case you could of course just define test environment variables, but it can become confusing when the configuration is divided into different places. Not to mention that you might not want (or be able to) read any file in a test environment.

@Component
@Profile("test")
public class ProcessorFake implements Processor {

// Implement without actually reading from a file
}

@Component
@Profile("qa", "prod", "dev")
public class ProcessorClass implements Processor {
// Real class used with other profiles
}

How to setup environment variable via Junit?

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.



Related Topics



Leave a reply



Submit