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.
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringApplicationClassWithMainMethod.class)
public class XYZServiceIT {
@Test
public void test1() {...}
@Test
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.
UPDATE
To pass environment variables to maven for your integration test use the following:
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?)I hope that helps. You can also change pom.xml profiles if needed but i wouldn't recommend that.