NetworkUtils { public static int getNextAvailablePort(InetAddress address) { return getNextAvailablePort(address, PortAllocator.INSTANCE); } private  NetworkUtils(); static InetAddress getLocalhost(); static InetAddress getInetAddressByName(String name); static int getNextAvailablePort(InetAddress address);  }
@Test public void getNextAvailablePort_never_returns_the_same_port_in_current_jvm() { Set<Integer> ports = new HashSet<>(); for (int i = 0; i < 100; i++) { int port = getNextAvailablePort(getLoopbackAddress()); assertThat(port).isGreaterThan(1023); ports.add(port); } assertThat(ports).hasSize(100); }
@Test public void getNextAvailablePort_retries_to_get_available_port_when_port_has_already_been_allocated() { NetworkUtils.PortAllocator portAllocator = mock(NetworkUtils.PortAllocator.class); when(portAllocator.getAvailable(any(InetAddress.class))).thenReturn(9_000, 9_000, 9_000, 9_100); InetAddress address = getLoopbackAddress(); assertThat(getNextAvailablePort(address, portAllocator)).isEqualTo(9_000); assertThat(getNextAvailablePort(address, portAllocator)).isEqualTo(9_100); }
@Test public void getNextAvailablePort_does_not_return_special_ports() { NetworkUtils.PortAllocator portAllocator = mock(NetworkUtils.PortAllocator.class); when(portAllocator.getAvailable(any(InetAddress.class))).thenReturn(900, 2_049, 4_045, 6_000, 1_059); assertThat(getNextAvailablePort(getLoopbackAddress(), portAllocator)).isEqualTo(1_059); }
@Test public void getNextAvailablePort_throws_ISE_if_too_many_attempts() { NetworkUtils.PortAllocator portAllocator = mock(NetworkUtils.PortAllocator.class); when(portAllocator.getAvailable(any(InetAddress.class))).thenReturn(900); expectedException.expect(IllegalStateException.class); expectedException.expectMessage("Fail to find an available port on "); getNextAvailablePort(getLoopbackAddress(), portAllocator); }