### Question:
HostNameKeyGenerator implements KeyGenerator { static void initWorkerId() { InetAddress address; Long workerId; try { address = InetAddress.getLocalHost(); } catch (final UnknownHostException e) { throw new IllegalStateException("Cannot get LocalHost InetAddress, please check your network!"); } String hostName = address.getHostName(); try { workerId = Long.valueOf(hostName.replace(hostName.replaceAll("\\d+$", ""), "")); } catch (final NumberFormatException e) { throw new IllegalArgumentException(String.format("Wrong hostname:%s, hostname must be end with number!", hostName)); } DefaultKeyGenerator.setWorkerId(workerId); }  @Override Number generateKey();  }### Answer:
@Test public void assertRightHostName() throws UnknownHostException, NoSuchFieldException, IllegalAccessException { PowerMockito.mockStatic(InetAddress.class); PowerMockito.when(InetAddress.getLocalHost()).thenReturn(rightAddress); HostNameKeyGenerator.initWorkerId(); Field workerIdField = DefaultKeyGenerator.class.getDeclaredField("workerId"); workerIdField.setAccessible(true); assertThat(workerIdField.getLong(DefaultKeyGenerator.class), is(233L)); }
@Test public void assertUnknownHost() throws UnknownHostException { PowerMockito.mockStatic(InetAddress.class); PowerMockito.when(InetAddress.getLocalHost()).thenThrow(new UnknownHostException()); exception.expect(IllegalStateException.class); exception.expectMessage("Cannot get LocalHost InetAddress, please check your network!"); HostNameKeyGenerator.initWorkerId(); }
@Test public void assertWrongHostName() throws UnknownHostException { PowerMockito.mockStatic(InetAddress.class); PowerMockito.when(InetAddress.getLocalHost()).thenReturn(wrongAddress); exception.expect(IllegalArgumentException.class); exception.expectMessage(String.format("Wrong hostname:%s, hostname must be end with number!", wrongAddress.getHostName())); HostNameKeyGenerator.initWorkerId(); }