JsonCodec implements Codec<ServiceInstance> { @Override public void serialize(ServiceInstance instance, OutputStream sink) throws IOException { Writer writer = new OutputStreamWriter(sink, ENCODING); try { gson.toJson(new ServiceInstanceSchema(instance), writer); } catch (JsonIOException e) { throw new IOException(String.format("Problem serializing %s to JSON", instance), e); } writer.flush(); } JsonCodec();   JsonCodec(Gson gson); @Override void serialize(ServiceInstance instance, OutputStream sink); @Override ServiceInstance deserialize(InputStream source);  }
@Test public void testJsonCompatibility() throws IOException { ServiceInstance instance = new ServiceInstance( new Endpoint("foo", 1000), ImmutableMap.of("http", new Endpoint("foo", 8080)), Status.ALIVE).setShard(42); ByteArrayOutputStream results = new ByteArrayOutputStream(); STANDARD_JSON_CODEC.serialize(instance, results); assertEquals( "{\"serviceEndpoint\":{\"host\":\"foo\",\"port\":1000}," + "\"additionalEndpoints\":{\"http\":{\"host\":\"foo\",\"port\":8080}}," + "\"status\":\"ALIVE\"," + "\"shard\":42}", results.toString()); }
@Test public void testInvalidSerialize() { Gson gson = PowerMock.createMock(Gson.class); gson.toJson(EasyMock.isA(Object.class), EasyMock.isA(Appendable.class)); EasyMock.expectLastCall().andThrow(new JsonIOException("error")); PowerMock.replay(gson); ServiceInstance instance = new ServiceInstance(new Endpoint("foo", 1000), ImmutableMap.of(), Status.ALIVE); try { new JsonCodec(gson).serialize(instance, new ByteArrayOutputStream()); fail(); } catch (IOException e) { } PowerMock.verify(gson); }