Class TestSocketUtils

java.lang.Object
org.springframework.test.util.TestSocketUtils

public class TestSocketUtils extends Object
Simple utility for finding available TCP ports on localhost for use in integration testing scenarios.

This is a limited form of org.springframework.util.SocketUtils, which has been deprecated since Spring Framework 5.3.16 and removed in Spring Framework 6.0.

TestSocketUtils can be used in integration tests which start an external server on an available random port. However, these utilities make no guarantee about the subsequent availability of a given port and are therefore unreliable. Instead of using TestSocketUtils to find an available local port for a server, it is recommended that you rely on a server's ability to start on a random ephemeral port that it selects or is assigned by the operating system. To interact with that server, you should query the server for the port it is currently using.

Since:
5.3.24
Author:
Sam Brannen, Ben Hale, Arjen Poutsma, Gunnar Hillert, Gary Russell, Chris Bono
  • Constructor Details

    • TestSocketUtils

      public TestSocketUtils()
      Although TestSocketUtils consists solely of static utility methods, this constructor is intentionally public.
      Rationale

      Static methods from this class may be invoked from within XML configuration files using the Spring Expression Language (SpEL) and the following syntax.

      
       <bean id="myBean" ... p:port="#{T(org.springframework.test.util.TestSocketUtils).findAvailableTcpPort()}" />
       

      If this constructor were private, you would be required to supply the fully qualified class name to SpEL's T() function for each usage. Thus, the fact that this constructor is public allows you to reduce boilerplate configuration with SpEL as can be seen in the following example.

      
       <bean id="socketUtils" class="org.springframework.test.util.TestSocketUtils" />
       <bean id="myBean" ... p:port="#{socketUtils.findAvailableTcpPort()}" />
       
  • Method Details

    • findAvailableTcpPort

      public static int findAvailableTcpPort()
      Find an available TCP port randomly selected from the range [1024, 65535].
      Returns:
      an available TCP port number
      Throws:
      IllegalStateException - if no available port could be found