如何在集成测试运行之前加载环境变量以加载应用程序上下文
How do I load environment variables to load application context before integration test runs
我正在使用 Spring Boot 2.4.0 开发多模块 Maven 项目。我已经为一个模块编写了集成测试。测试 class 看起来与此类似。
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringApplicationClassWithMainMethod.class)
public class XYZServiceIT {
@Test
public void test1() {...}
@Test
public void test2() {...}
}
到 运行 SpringApplicationClassWithMainMethod.class 即,为了加载应用程序上下文,我需要在 eclipse 中设置的几个环境变量。因此,为了 运行 在加载 SpringApplicationClassWithMainMethod.class 时进行上述集成测试,我需要在加载应用程序上下文之前使用这些环境变量。
试验-1:
我尝试使用 @TestPropertySource(properties = {"key1=val1", "key2=val2"}) 注释,但没有用。
试验二:
我也尝试过静态块来设置没有工作的环境变量。
试验 3:
我还尝试将 @ContextConfiguration 与 ApplicationContextInitializer class 一起使用,但效果不佳。
所有这些使用 Maven 构建项目的尝试只会导致
IllegalState Failed to load ApplicationContext
上述测试的错误 class。有什么方法可以在加载应用程序上下文之前加载环境变量?
我认为 maven 中集成测试的正确 class 命名约定是 XYZServiceIT
因为 *Test
已经为单元测试保留了 运行 在应用程序上下文之前.如果需要,您可以在 Maven pom 中更改它,或者只是坚持使用常规命名。
更新
要将环境变量传递给 Maven 以进行集成测试,请使用以下命令:
- 确保您从 eclipse marketplace 安装了 M2E(在菜单 > 帮助 > eclipse marketplace 中找到)
- 右键单击您的项目 > 运行 As ... > 4 Maven Build ...
PS:之后您可以在绿色箭头下拉列表下方的顶部和 运行 配置设置中找到您的 运行 配置,如果您需要重新 运行 以后的测试
- 使用
verify -Dkey=val
内联(对于 maven 目标命令)或在底部变量部分配置 maven 环境参数。都适用于单元和集成测试。环境通常不适用于测试阶段。 (如果您没有 JDK 作为 运行ner,您将收到错误消息。如果需要,请按照此 post 进行修复:No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK? )
希望对您有所帮助。如果需要,您还可以更改 pom.xml 配置文件,但我不建议这样做。
我正在使用 Spring Boot 2.4.0 开发多模块 Maven 项目。我已经为一个模块编写了集成测试。测试 class 看起来与此类似。
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringApplicationClassWithMainMethod.class)
public class XYZServiceIT {
@Test
public void test1() {...}
@Test
public void test2() {...}
}
到 运行 SpringApplicationClassWithMainMethod.class 即,为了加载应用程序上下文,我需要在 eclipse 中设置的几个环境变量。因此,为了 运行 在加载 SpringApplicationClassWithMainMethod.class 时进行上述集成测试,我需要在加载应用程序上下文之前使用这些环境变量。
试验-1: 我尝试使用 @TestPropertySource(properties = {"key1=val1", "key2=val2"}) 注释,但没有用。
试验二: 我也尝试过静态块来设置没有工作的环境变量。
试验 3: 我还尝试将 @ContextConfiguration 与 ApplicationContextInitializer class 一起使用,但效果不佳。
所有这些使用 Maven 构建项目的尝试只会导致
IllegalState Failed to load ApplicationContext
上述测试的错误 class。有什么方法可以在加载应用程序上下文之前加载环境变量?
我认为 maven 中集成测试的正确 class 命名约定是 XYZServiceIT
因为 *Test
已经为单元测试保留了 运行 在应用程序上下文之前.如果需要,您可以在 Maven pom 中更改它,或者只是坚持使用常规命名。
更新
要将环境变量传递给 Maven 以进行集成测试,请使用以下命令:
- 确保您从 eclipse marketplace 安装了 M2E(在菜单 > 帮助 > eclipse marketplace 中找到)
- 右键单击您的项目 > 运行 As ... > 4 Maven Build ... PS:之后您可以在绿色箭头下拉列表下方的顶部和 运行 配置设置中找到您的 运行 配置,如果您需要重新 运行 以后的测试
- 使用
verify -Dkey=val
内联(对于 maven 目标命令)或在底部变量部分配置 maven 环境参数。都适用于单元和集成测试。环境通常不适用于测试阶段。 (如果您没有 JDK 作为 运行ner,您将收到错误消息。如果需要,请按照此 post 进行修复:No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK? )
希望对您有所帮助。如果需要,您还可以更改 pom.xml 配置文件,但我不建议这样做。