NetworkAddressValidator implements Validator<NetworkAddress> { @Override public boolean isValid(NetworkAddress networkAddress) { if (networkAddress == null) { return false; } String ip = networkAddress.ip(); int port = networkAddress.port(); if (ip == null || ip.isEmpty() || port <= 0 || port > 65535) { return false; } InetAddressValidator inetAddressValidator = InetAddressValidator.getInstance(); return inetAddressValidator.isValid(ip); } @Inject  NetworkAddressValidator(); @Override boolean isValid(NetworkAddress networkAddress);  }
@Test public void shouldCheckInvalidWhenInvalidIpGiven() throws Exception { NetworkAddress networkAddress = NetworkAddress.builder() .ip("945.333.0.257") .port(4356) .build(); boolean valid = networkAddressValidator.isValid(networkAddress); assertThat(valid).isFalse(); }
@Test public void shouldCheckValidWhenValidIpAndPortGiven() throws Exception { NetworkAddress networkAddress = NetworkAddress.builder() .ip("192.168.1.45") .port(4356) .build(); boolean valid = networkAddressValidator.isValid(networkAddress); assertThat(valid).isTrue(); }
@Test public void shouldCheckInvalidWhenNullGiven() throws Exception { boolean valid = networkAddressValidator.isValid(null); assertThat(valid).isFalse(); }
@Test public void shouldCheckInvalidWhenNullIpGiven() throws Exception { NetworkAddress networkAddress = NetworkAddress.builder() .ip("") .port(4356) .build(); boolean valid = networkAddressValidator.isValid(networkAddress); assertThat(valid).isFalse(); }
@Test public void shouldCheckInvalidWhenEmptyIpGiven() throws Exception { NetworkAddress networkAddress = NetworkAddress.builder() .ip("") .port(4356) .build(); boolean valid = networkAddressValidator.isValid(networkAddress); assertThat(valid).isFalse(); }
@Test public void shouldCheckInvalidWhenNegativePortNumberGiven() throws Exception { NetworkAddress networkAddress = NetworkAddress.builder() .ip("192.168.1.45") .port(-4356) .build(); boolean valid = networkAddressValidator.isValid(networkAddress); assertThat(valid).isFalse(); }
@Test public void shouldCheckInvalidWhenPortNumberExceedingLimitGiven() throws Exception { NetworkAddress networkAddress = NetworkAddress.builder() .ip("192.168.1.45") .port(4356545) .build(); boolean valid = networkAddressValidator.isValid(networkAddress); assertThat(valid).isFalse(); }