如何在testpropertysource中获取SpringBootTest.WebEnvironment.RANDOM_PORT其他属性?

时间:2019-12-11 16:35:51

标签: spring spring-boot unit-testing

我正在编写一个使用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'

我该怎么做?

1 个答案:

答案 0 :(得分:1)

您是否尝试过使用$ {local.server.port}?否则,您可以使用系统设置属性 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");
   }
}