PortUtil { public static int validateOrGetNew(int preferredPort) { if (preferredPort == 0 || isPortInUse(preferredPort)) { if (preferredPort != 0) { LOG.warn("Port {} already in use, system will automatically look for a new one.", preferredPort); } try (ServerSocket ss = new ServerSocket(0)) { return ss.getLocalPort(); } catch (IOException e) { LOG.error(ERROR_MESSAGE, e); throw new RuntimeException(ERROR_MESSAGE); } } return preferredPort; }  static int validateOrGetNew(int preferredPort);  }
@Test public void testValidateOrGetNewWithPreferredNotAvailable() { int result1 = PortUtil.validateOrGetNew(0); try (ServerSocket ss = new ServerSocket(result1)) { int result = PortUtil.validateOrGetNew(result1); assertThat(result).isNotEqualTo(result1); } catch (Exception x) { fail("Port allocation should have work!"); } }
@Test public void testValidateOrGetNewWithZero() { int result1 = PortUtil.validateOrGetNew(0); assertThat(result1).isNotEqualTo(0); }
@Test public void testValidateOrGetNewWithAvailablePreferredPort() { int result = PortUtil.validateOrGetNew(0); int result2 = PortUtil.validateOrGetNew(result); assertThat(result2).isEqualTo(result); }