How do I load environment variables to load application context before integration test runs

Tags: , , , ,

I’m working on multi-module maven project using Spring Boot 2.4.0. I have written integration tests for a module. The test class looks similar to this.

@SpringBootTest(classes = SpringApplicationClassWithMainMethod.class)
public class XYZServiceIT {

public void test1() {...}

public void test2() {...}

To run the SpringApplicationClassWithMainMethod.class i.e., in order to load the Application context I need few environment variables that I set in eclipse. So, in order to run the above integration test while loading the SpringApplicationClassWithMainMethod.class I need those environment variables before the Application context is loaded.

Trial-1: I have tried using @TestPropertySource(properties = {“key1=val1”, “key2=val2”}) annotation, that didn’t work.

Trial-2: I have also tried the static block to set environment variables which didnt work.

Trial-3: I also tried using the @ContextConfiguration with a ApplicationContextInitializer class, that didnt work as well.

All these attempts to build the project using maven only lead to a

IllegalState Failed to load ApplicationContext

error for the above test class. Is there any way I could load the environment variables before the Application context gets loaded?


I think the correct class naming convention for Integration tests in maven would be XYZServiceIT since *Test is reserved for unit tests already which are run before application context. You can change that if needed in your maven pom or simply stick with the conventional naming.


To pass environment variables to maven for your integration test use the following:

  1. make sure you installed M2E from eclipse marketplace (found in menu > help > eclipse marketplace)

m2e plugin from marketplace

  1. right click your project > Run As … > 4 Maven Build … PS: afterwards you can find your run configuration at the top underneath the dropdown of the green arrow and in the run configuration settings if you need to rerun the tests in the future

first maven build from rightclick on project

  1. configure maven environment parameters either inline (for the maven goal command) with verify -Dkey=val or in the bottom variable section. both work for unit and integrationtest. environment typically does NOT work for test stage. (If you don’t have an JDK as the runner you will get an error. Follow this post to fix it if needed: No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?)

mvn goal settings with environment vars

I hope that helps. You can also change pom.xml profiles if needed but i wouldn’t recommend that.

Source: stackoverflow