Facundo Laxalde
Facundo Laxalde

Reputation: 357

is there a way to push environment variables when using org.springframework.boot.test.context.SpringBootTest?

I have this test class:

import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;


@SpringBootTest
class ThisTestClass {

@Test
void contextLoads() {}

}

when contextLoads(), a pice of code as following is triggered

private String envVar = System.getenv("ENV_VAR");

which is returning null, which is messing with my test, therefore I need a way to push environment variables at some point of time before executing this test. doing this via the IDE env settings or the console is not an option, since this is going to be executed by jenkins as well.

I have tryed:

import org.springframework.test.context.TestPropertySource;
@TestPropertySource(properties = {"ENV_VAR = some_var"})

and

    static {
    System.setProperty("ENV_VAR", "some_var");
    }

without any luck, any ideas?

Upvotes: 3

Views: 7531

Answers (1)

Dirk Deyne
Dirk Deyne

Reputation: 6936

Both should work...

  • set environment variable via static initialization
  • set environment variable via properties
@SpringBootTest(properties = { "bar = foo" , "foobar = foobar"} )
class SoTestEnvironmentVariablesApplicationTests {

    static {
        System.setProperty("foo","bar");
    }

    @Autowired Environment environment;

    @Test
    void loadEnvironmentVariables() {
        assertNotNull(environment);
        assertEquals("bar" , environment.getProperty("foo"));
        assertEquals("foo" , environment.getProperty("bar"));
        assertEquals("foobar" , environment.getProperty("foobar"));
    }

}

Upvotes: 0

Related Questions