[英]Add environment property to @SpringBootTest before application.properties evaluation?
Is it possible to add a "dynamic" property from a class to application.properties
before they are evaluated?是否可以在评估之前将 class 中的“动态”属性添加到application.properties
?
I want to achieve the following: find a free port on the system, inject it as property mockPort
into the spring lifecycle, and reuse this port to override a property from application.properties
using @TestPropertySource
, as follows:我想实现以下目标:在系统上找到一个空闲端口,将其作为属性mockPort
注入 spring 生命周期,并重用此端口以使用@TestPropertySource
覆盖application.properties
中的属性,如下所示:
@SpringBootTest
@TestPropertySource(properties = "web.client.url=localhost:${mockPort}/path")
public class MyWebTest {
//TODO how to write the port into ${mockPort} property?
private static final PORT = SocketUtils.findAvailableTcpPort();
@BeforeEach
public void init() {
MockWebServer mock = new MockWebServer();
mock.start(PORT);
}
@Test
public void test() {
service.runWebRequest();
}
}
The service under test can be any client that makes use of @Value("${web.client.url})
. And as the free port is found dynamically during runtime, I have to somehow inject it into that property.被测服务可以是任何使用@Value("${web.client.url})
的客户端。由于空闲端口是在运行时动态找到的,我必须以某种方式将其注入该属性。
How can I achieve this?我怎样才能做到这一点?
You can use Spring Framework's @DynamicPropertySource
for this purpose.为此,您可以使用 Spring 框架的@DynamicPropertySource
。 It's described in this blog post . 此博客文章中对此进行了描述。
In the case of MyWebTest
, the dynamic property source would look something like this:在MyWebTest
的情况下,动态属性源看起来像这样:
@DynamicPropertySource
static void mockPortProperty(DynamicPropertyRegistry registry) {
registry.add("mockPort", () -> PORT);
}
Maybe you prefer to start a single MockWebServer for all test classes, instead of starting a new server for each test method.也许您更喜欢为所有测试类启动一个 MockWebServer,而不是为每个测试方法启动一个新服务器。 When this class is initialized, the static block starts a server and sets a system property to the server URL.初始化此 class 时,static 块启动服务器并将系统属性设置为服务器 URL。 System properties override properties from the application.properties
file. 系统属性会覆盖application.properties
文件中的属性。
@TestConfiguration
public class MockWebServerConfiguration {
private static final MockWebServer mockWebServer = new MockWebServer();
static {
int port = SocketUtils.findAvailableTcpPort();
mockWebServer.start(port);
System.setProperty("web.client.url", "localhost:" + port + "/path");
}
}
To include this configuration class in your integration test, annotate your test class with:要在您的集成测试中包含此配置 class,请使用以下命令注释您的测试 class:
@Import(MockWebServerConfiguration.class)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.