問題描述
我想在測試中覆蓋 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 設置的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!