简体   繁体   中英

How to get the SpringBootTest.WebEnvironment.RANDOM_PORT in a testpropertysource additional properties?

I am writing a test that uses SpringBootTest.WebEnvironment.RANDOM_PORT , but I need to use this port value in a property used by some external bean (ie that I cannot change).

I tried using {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 {
    ...
}

but I get java.lang.IllegalArgumentException: Not enough variable values available to expand 'local.server.port'

How can I do that?

Did you tried with ${local.server.port}? Otherwise, you can set property externalProp.accessUrl by using System.

@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");
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM