title: Resolving port already in use in a Spring boot test DEFINED PORT
body: <p>I have a spring boot application that fires up and executes a class that listens to <strong>Application Ready event</strong> to call an <strong>external service</strong> to fetch some data and then use that data to push some rules to the classpath for execution. For local testing we have <strong>mocked the external service</strong> within our application which works fine during the application startup.</p>
  
  <p>The <strong>issue is while testing</strong> the application by running it with <strong>spring boot test</strong> annotation and embedded jetty container either on :</p>
  
  <ul>
  <li>RANDOM PORT</li>
  <li>DEFINED PORT</li>
  </ul>
  
  <p>In case of <em>RANDOM PORT</em>, at the application startup, it picks up the url for the mock service from the properties file at a defined port and has no clue where the embedded container is running since it is randomly picked up, hence failing to give response.</p>
  
  <p>In case of <em>DEFINED PORT</em>, for the first test case file it runs successfully, but the moment next file is picked up, it fails saying the port is already in use.</p>
  
  <blockquote>
    <p>The test cases are partitioned logically in multiple files and need
    the external service to be called before the container starts to load
    the rules.</p>
  </blockquote>
  
  <p>How can I either share the embedded container between test files in case of using defined port or refactor my application code instead to get hold of the random port while starting up during the test case execution.</p>
  
  <p>Any help would be appreciated.</p>
  
  <p><strong>Application Startup code :</strong></p>
  
  <pre><code>@Component
  public class ApplicationStartup implements ApplicationListener&lt;ApplicationReadyEvent&gt; {
  
  @Autowired
  private SomeService someService;
  
  @Override
  public void onApplicationEvent(ApplicationReadyEvent arg0) {
  
      try {
          someService.callExternalServiceAndLoadData();
      }
      catch (Execption e) {}
      }
   }
  </code></pre>
  
  <p><strong>Test Code Annotations: Test1</strong></p>
  
  <pre><code>@RunWith(SpringRunner.class)
  @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
  @TestPropertySource("classpath:test-application.properties")
  public class Test1 {
  
      @Autowired
      private TestRestTemplate restTemplate;
  
      @Test
      public void tc1() throws IOException {.....}
  </code></pre>
  
  <p><strong>Test Code Annotations: Test2</strong></p>
  
  <pre><code>@RunWith(SpringRunner.class)
  @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
  @TestPropertySource("classpath:test-application.properties")
  public class Test2 {
  
      @Autowired
      private TestRestTemplate restTemplate;
  
      @Test
      public void tc1() throws IOException {.....}
  </code></pre>