Spring Boot 如何使用WebEnvironment.RANDOM_PORT获取第二个随机端口?

fhg3lkii  于 12个月前  发布在  Spring
关注(0)|答案(1)|浏览(116)

我有一个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文件中使用的值。

qv7cva1a

qv7cva1a1#

经过一些研究,我发现我可以在这个特定的测试用例中使用类和方法org.springframework.test.util.TestSocketUtils.findAvailableTcpPort(),它是在SocketUtils被删除后引入的。
这样我就实现了一个RandomPortInitializer

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public abstract class AbstractIntegrationTest {

  // This value will be set later by the RandomPortInitializer
  @Value("${server.internalPort}")
  int internalPort;

  ...

  public static class RandomPortInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {

      @Override
      public void initialize(ConfigurableApplicationContext applicationContext) {
        int randomPort = TestSocketUtils.findAvailableTcpPort();
        TestPropertySourceUtils.addInlinedPropertiesToEnvironment(applicationContext,
              "server.internalPort=" + randomPort);
      }
    }
  ...
}

字符串
我在我的具体测试类上使用了这个初始化器,在那里我可以访问internalPort值。

@DisplayName("Do some tests")
@ContextConfiguration(initializers = {RandomPortInitializer.class})
class MyIntegrationTest extends AbstractIntegrationTest {
...

相关问题