使用动态值覆盖 Junit 测试中的默认 Spring-Boot application.properties 设置 [英] Override default Spring-Boot application.properties settings in Junit Test with dynamic value

查看:30
本文介绍了使用动态值覆盖 Junit 测试中的默认 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 测试中的默认 Spring-Boot application.properties 设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆