title: Unable to set runtime Local Server Port in Spring Boot Test 1.5
body: <p>I am using Spring Boot 1.5 for my application. In integration testing I want to fetch the runtime port number of the web server(note: TestRestTemplate is not useful in my case.). There are a few approaches I have tried but none of them seem to work. Below are my approaches.</p>
  
  <p><strong>First Approach</strong></p>
  
  <pre><code>@SpringBootTest(classes = TestConfig.class, webEnvironment =WebEnvironment.DEFINED_PORT)
  public class RestServiceTest {
  
  @LocalServerPort      
  protected int port;
  </code></pre>
  
  <p>In my <code>src/main/resources/config/application.properties</code> file I have defined server port as</p>
  
  <blockquote>
    <p>server.port = 8081</p>
  </blockquote>
  
  <p>But With this code I am getting error</p>
  
  <blockquote>
    <p>Could not resolve placeholder 'local.server.port' in value "${local.server.port}"</p>
  </blockquote>
  
  <p><strong>Second Approach</strong></p>
  
  <p>I have changed</p>
  
  <blockquote>
    <p>webEnvironment =WebEnvironment.DEFINED_PORT</p>
  </blockquote>
  
  <p>to</p>
  
  <blockquote>
    <p>webEnvironment =WebEnvironment.RANDOM_PORT</p>
  </blockquote>
  
  <p>and in my <code>src/main/resources/config/application.properties</code> file I have defined </p>
  
  <blockquote>
    <p>server.port = 0</p>
  </blockquote>
  
  <p>This throws the same as error as the first approach.</p>
  
  <p><strong>Third Approach</strong></p>
  
  <p>In third approach I have tried to use </p>
  
  <pre><code>protected int port;
  
  @Autowired
  Environment environment
  
  this.port = this.environment.getProperty("local.server.port");
  </code></pre>
  
  <p>this returns <code>null</code> value</p>
  
  <p><strong>Fourth Approach</strong></p>
  
  <p>Lastly I have tried to use <code>ApplicationEvents</code> to find out the port number by creating an event listener to listen to <code>EmbeddedServletContainerIntialize</code></p>
  
  <pre><code>@EventListener(EmbeddedServletContainerInitializedEvent.class)
  public void onApplicationEvent(EmbeddedServletContainerInitializedEvent event) {
  this.port = event.getEmbeddedServletContainer().getPort();
  }
  
  public int getPort() {
  return this.port;
  } 
  </code></pre>
  
  <p>Added the same to <code>TestConfig</code></p>
  
  <p>Now, In my test class I have tried use this listener to get the port</p>
  
  <pre><code>@SpringBootTest(classes = TestConfig.class, webEnvironment =WebEnvironment.RANDOM_PORT)
  public class RestServiceTest {
  
  protected int port;
  
  @Autowired
  EmbeddedServletContainerIntializedEventListener embeddedServletcontainerPort;
  
  this.port = this.embeddedServletcontainerPort.getPort();
  </code></pre>
  
  <p>this returns <code>0</code>. Also, I have found out listener event is never triggered.</p>
  
  <p>It is very straight forward as in the docs and other posts but somehow It is not working for me. Help is much appreciated.</p>