### Question:
LoadPublicIpForInstanceOrNull extends CacheLoader<RegionAndName, String> { @Override public String load(final RegionAndName key) throws Exception { try { return Iterables.find(client.getElasticIPAddressApi().get().describeAddressesInRegion(key.getRegion()), new Predicate<PublicIpInstanceIdPair>() { @Override public boolean apply(PublicIpInstanceIdPair input) { return key.getName().equals(input.getInstanceId()); } }).getPublicIp(); } catch (NoSuchElementException e) { return null; } } @Inject  LoadPublicIpForInstanceOrNull(EC2Api client); @Override String load(final RegionAndName key);  }### Answer:
@Test public void testReturnsPublicIpOnMatch() throws Exception { EC2Api client = createMock(EC2Api.class); ElasticIPAddressApi ipClient = createMock(ElasticIPAddressApi.class); expect(client.getElasticIPAddressApi()).andReturn((Optional) Optional.of(ipClient)).atLeastOnce(); expect(ipClient.describeAddressesInRegion("region")).andReturn( ImmutableSet.<PublicIpInstanceIdPair> of(new PublicIpInstanceIdPair("region", "1.1.1.1", "i-blah", null))) .atLeastOnce(); replay(client); replay(ipClient); LoadPublicIpForInstanceOrNull parser = new LoadPublicIpForInstanceOrNull(client); assertEquals(parser.load(new RegionAndName("region", "i-blah")), "1.1.1.1"); verify(client); verify(ipClient); }
@Test public void testReturnsNullWhenNotFound() throws Exception { EC2Api client = createMock(EC2Api.class); ElasticIPAddressApi ipClient = createMock(ElasticIPAddressApi.class); expect(client.getElasticIPAddressApi()).andReturn((Optional) Optional.of(ipClient)).atLeastOnce(); expect(ipClient.describeAddressesInRegion("region")).andReturn(ImmutableSet.<PublicIpInstanceIdPair> of()) .atLeastOnce(); replay(client); replay(ipClient); LoadPublicIpForInstanceOrNull parser = new LoadPublicIpForInstanceOrNull(client); assertEquals(parser.load(new RegionAndName("region", "i-blah")), null); verify(client); verify(ipClient); }
@Test public void testReturnsNullWhenNotAssigned() throws Exception { EC2Api client = createMock(EC2Api.class); ElasticIPAddressApi ipClient = createMock(ElasticIPAddressApi.class); expect(client.getElasticIPAddressApi()).andReturn((Optional) Optional.of(ipClient)).atLeastOnce(); expect(ipClient.describeAddressesInRegion("region")).andReturn( ImmutableSet.<PublicIpInstanceIdPair> of(new PublicIpInstanceIdPair("region", "1.1.1.1", null, null))) .atLeastOnce(); replay(client); replay(ipClient); LoadPublicIpForInstanceOrNull parser = new LoadPublicIpForInstanceOrNull(client); assertEquals(parser.load(new RegionAndName("region", "i-blah")), null); verify(client); verify(ipClient); }