DefaultMachineId implements MachineId { @Override public int getId() { try { byte[] a = InetAddress.getLocalHost().getAddress(); log.debug("Localhost IP address: {}", InetAddress.getLocalHost().getHostAddress()); int machineId = (Byte.toUnsignedInt(a[2]))<<8 | Byte.toUnsignedInt(a[3]); log.debug("Calculated machineID: {}", machineId); return machineId; } catch (UnknownHostException e) { String message = "Failed to process machine id."; log.error(message, e); throw new CamflakeException(message, e); } }  @Override int getId();  }
@Test public void testGetId(@Mocked InetAddress inetAddress) { new Expectations() { { inetAddress.getAddress(); result = new byte[]{127, 0, 0, 1}; inetAddress.getHostAddress(); result = "test_host"; } }; DefaultMachineId testee = new DefaultMachineId(); assertThat(testee.getId(), is(1)); }
@Test(expected = CamflakeException.class) public void testGetIdThrowsExceptionWhenErrorOccurs() throws Exception { new Expectations(InetAddress.class) { { InetAddress.getLocalHost(); result = new UnknownHostException(); } }; DefaultMachineId testee = new DefaultMachineId(); testee.getId(); }