我有一个Sping Boot 应用程序,我从标准端口机制开始,即将属性值server.port
设置为一个固定的数字,例如8081。我设法在Sping Boot 应用程序中公开了第二个/单独的端口,在此端口上可以使用其他(读作:内部)REST端点。因此,我引入了属性server.internalPort
。
当运行@SpringBootTest
集成测试时,我可以通过webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT
轻松地随机化server.port
值,但我也需要以某种方式随机化属性server.internalPort
的值。
有没有一种简单的方法可以在测试启动时注册一个属性值进行随机化?例如,我的测试看起来像这样:
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
...
public abstract class AbstractSomethingIntegrationTest {
@LocalServerPort
private int port;
@Value("${server.internalPort}")
private int internalPort;
字符串
变量port
得到一个随机值,但internalPort
没有。它得到我在integrationtest/resources/application.yml
文件中使用的值。
1条答案
按热度按时间qv7cva1a1#
经过一些研究,我发现我可以在这个特定的测试用例中使用类和方法
org.springframework.test.util.TestSocketUtils.findAvailableTcpPort()
,它是在SocketUtils
被删除后引入的。这样我就实现了一个
RandomPortInitializer
:字符串
我在我的具体测试类上使用了这个初始化器,在那里我可以访问
internalPort
值。型