2

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?

Facundo Laxalde
  • 305
  • 5
  • 18
  • Does this answer your question? [How to set environment variable or system property in spring tests?](https://stackoverflow.com/questions/11306951/how-to-set-environment-variable-or-system-property-in-spring-tests) – Ryuzaki L Dec 11 '19 at 14:22
  • Hey, no, TestPropertySource did not worked either. I was trying that after writing the question. for now the only strategi I am considering is stop using System.getenv – Facundo Laxalde Dec 11 '19 at 14:25

1 Answers1

1

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

}
Dirk Deyne
  • 6,048
  • 1
  • 15
  • 32
  • 1
    Hey Dirk, thanks for your answer. It is not working.still the same error – Facundo Laxalde Dec 12 '19 at 10:07
  • @FacundoLaxalde above code is working [ref github](https://github.com/dirkdeyne/push-environment-variables-in-test/blob/master/src/test/java/so/demo/pushenvironmentvariablesintest/PushEnvironmentVariablesInTestApplicationTests.java) – Dirk Deyne Dec 12 '19 at 11:26
  • 4
    I'm facing the same issue. `System.getenv("ENV_VAR")` is different than `environment.getProperty("ENV_VAR")` – brianestey Aug 04 '20 at 07:29