首页 > 解决方案 > 如何在 testpropertysource 附加属性中获取 SpringBootTest.WebEnvironment.RANDOM_PORT?

问题描述

我正在编写一个使用 的测试SpringBootTest.WebEnvironment.RANDOM_PORT,但我需要在某个外部 bean 使用的属性中使用此端口值(即我无法更改)。

我尝试使用{local.server.port}

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@TestPropertySource(properties = {
    "externalProp.accessUrl=http://localhost:{local.server.port}}/foo"
})
public class MyTest {
    ...
}

但我明白了java.lang.IllegalArgumentException: Not enough variable values available to expand 'local.server.port'

我怎样才能做到这一点?

标签: springspring-bootunit-testing

解决方案


你试过 ${local.server.port} 吗?否则,您可以使用 System.xml 设置属性externalProp.accessUrl

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class MyTest {
    @LocalServerPort
    private static int randomServerPort;


    @Before
    public void setUp(){

 System.setProperty("externalProp.accessUrl","http://localhost:"+randomServerPort+"/foo");
   }
}

推荐阅读