Override default Spring-Boot application.properties settings in Junit Test with dynamic value(使用动态值覆盖 Junit Test 中的默认 Spring-Boot application.properties 设置)
问题描述
我想在测试中覆盖 application.properties 中定义的属性,但 @TestPropertySource 只允许提供预定义的值.
I want to override properties defined in application.properties in tests, but @TestPropertySource only allows to provide predefined values.
我需要在随机端口 N 上启动服务器,然后将此端口传递给 spring-boot 应用程序.端口必须是临时的,以允许同时在同一主机上运行多个测试.
What I need is to start a server on a random port N, then pass this port to spring-boot application. The port has to be ephemeral to allow running multiple tests on the same host at the same time.
我不是指嵌入式http服务器(jetty),而是在测试开始时启动的一些不同的服务器(例如zookeeper)并且被测试的应用程序必须连接到它.
I don't mean the embedded http server (jetty), but some different server that is started at the beginning of the test (e.g. zookeeper) and the application being tested has to connect to it.
实现这一目标的最佳方法是什么?
What's the best way to achieve this?
(这是一个类似的问题,但答案没有提到临时端口的解决方案 - 在 Junit 测试中覆盖默认 Spring-Boot application.properties 设置)
(here's a similar question, but answers do not mention a solution for ephemeral ports - Override default Spring-Boot application.properties settings in Junit Test)
推荐答案
从 Spring Framework 5.2.5 和 Spring Boot 2.2.6 开始,您可以在测试中使用 Dynamic Properties
:
As of Spring Framework 5.2.5 and Spring Boot 2.2.6 you can use Dynamic Properties
in tests:
@DynamicPropertySource
static void dynamicProperties(DynamicPropertyRegistry registry) {
registry.add("property.name", "value");
}
这篇关于使用动态值覆盖 Junit Test 中的默认 Spring-Boot application.properties 设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用动态值覆盖 Junit Test 中的默认 Spring-Boot application.properties 设置


- 如何使用WebFilter实现授权头检查 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01