2

I'm running a full SpringBoot Application using a random port in my SpringBootTest. I can retrieve the random port in my test class by using the annotation @LocalServerPort:

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ContextConfiguration(classes = {MyTest.LocalConfig.class})
public class MyTest {

  @LocalServerPort
  private Integer port;

Unfortunately I cannot retrieve the random port in my Configuration class, where I want to create test beans using the random port:

  @TestConfiguration
  public static class LocalConfig {

    @Bean
    public MyBean myBean(@Value("${local.server.port}") int port) {

Here I get this error:

Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 
'local.server.port' in value "${local.server.port}"
Matthias M
  • 12,906
  • 17
  • 87
  • 116

2 Answers2

4

Thanks to knoobie I've figured out this solution:

@Lazy
@TestConfiguration
public static class LocalConfig {

  @Bean
  public MyBean myBean(@Value("${local.server.port}") int port) {

If you use @Lazy, you can access the value local.server.port in the Configuration class.

The Beans in the Lazy Configuration class will be instantiated at last, so the port is available in that phase.

Unfortunately it is not possible to use the @Primary annotation in combination with @Lazy for overriding beans, because @Primary annotated beans are instantiated at an early phase.

Matthias M
  • 12,906
  • 17
  • 87
  • 116
0

The correct answer for me is from Baeldung:

https://www.baeldung.com/spring-boot-running-port#1-using-servletwebserverapplicationcontext

@Autowired
private ServletWebServerApplicationContext webServerAppCtxt;

@Test
public void given0AsServerPort_whenReadWebAppCtxt_thenGetThePort() {
    int port = webServerAppCtxt.getWebServer().getPort();
 
    assertTrue(port > 1023);
}
Janning Vygen
  • 8,877
  • 9
  • 71
  • 102