問(wèn)題描述
我想在測(cè)試中覆蓋 application.properties 中定義的屬性,但 @TestPropertySource 只允許提供預(yù)定義的值.
I want to override properties defined in application.properties in tests, but @TestPropertySource only allows to provide predefined values.
我需要在隨機(jī)端口 N 上啟動(dòng)服務(wù)器,然后將此端口傳遞給 spring-boot 應(yīng)用程序.端口必須是臨時(shí)的,以允許同時(shí)在同一主機(jī)上運(yùn)行多個(gè)測(cè)試.
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服務(wù)器(jetty),而是在測(cè)試開(kāi)始時(shí)啟動(dòng)的一些不同的服務(wù)器(例如zookeeper)并且被測(cè)試的應(yīng)用程序必須連接到它.
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.
實(shí)現(xiàn)這一目標(biāo)的最佳方法是什么?
What's the best way to achieve this?
(這是一個(gè)類(lèi)似的問(wèn)題,但答案沒(méi)有提到臨時(shí)端口的解決方案 - 在 Junit 測(cè)試中覆蓋默認(rèn) Spring-Boot application.properties 設(shè)置)
(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 開(kāi)始,您可以在測(cè)試中使用 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");
}
這篇關(guān)于使用動(dòng)態(tài)值覆蓋 Junit Test 中的默認(rèn) Spring-Boot application.properties 設(shè)置的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!