AvailablePortProvider { public int nextPort() { Set<Integer> notAvailable = Sets.newHashSet(); int port = from; while (port <= to) { if (!notAvailable.contains(port) && portChecker.apply(port)) { return port; } else { notAvailable.add(port); } port++; } throw new RuntimeException("Could not find an open port in range:(" + from + "," + to + ")"); } AvailablePortProvider(int from, int to, Function<Integer, Boolean> portChecker); static AvailablePortProvider between(int from, int to); int nextPort();  }
@Test public void testNextAvailablePort() throws Exception { AvailablePortProvider portGenerator = new AvailablePortProvider(MIN_PORT_NUMBER, MAX_PORT_NUMBER, p -> p % 2 == 0); int nextPort = portGenerator.nextPort(); assertTrue(nextPort >= MIN_PORT_NUMBER); assertTrue(nextPort <= MAX_PORT_NUMBER); assertTrue(nextPort % 2 == 0); }
@Test public void testNoPortAvailable() throws Exception { AvailablePortProvider portGenerator = new AvailablePortProvider(MIN_PORT_NUMBER, MIN_PORT_NUMBER + 3, p -> p > MAX_PORT_NUMBER); try { portGenerator.nextPort(); fail("Should not reach this line"); } catch (Exception e) { } }