使用org.springframework.boot.test.context.SpringBootTest时,有没有一种方法可以推送环境变量?

我有这个测试班:

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


@SpringBootTest
class ThisTestClass {

@Test
void contextLoads() {}

}

当contextLoads()时,会触发如下代码

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

这将返回null,这使我的测试陷入混乱,因此我需要一种在执行此测试之前的某个时间点推送环境变量的方法。通过IDE env设置或控制台执行此操作不是选项,因为这也将由jenkins执行。

我尝试过:

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

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

没有运气,有什么想法吗?

songqian729 回答:使用org.springframework.boot.test.context.SpringBootTest时,有没有一种方法可以推送环境变量?

两者都应该起作用...

  • 通过静态初始化设置环境变量
  • 通过属性设置环境变量
@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"));
    }

}
本文链接:https://www.f2er.com/2941585.html

大家都在问