Serializers { public static <T> String serialize(Serializer<T> serializer, T value, Charset charset) throws Exception { if(serializer instanceof StringSerializer) { return ((StringSerializer<T>)serializer).serialize(value, charset); }else{ ByteArrayOutputStream out = new ByteArrayOutputStream(); serializer.serialize(value, charset, out); return new String(out.toByteArray(), charset); } } private  Serializers(); static String serialize(Serializer<T> serializer, T value, Charset charset);  }
@Test public void shouldSerializeToStringUsingStringSerializerSpecificMethodIfSerializerIsOfSpecificInstance() throws Exception { StringSerializer serializer = mock(StringSerializer.class); when(serializer.serialize("arg", UTF8)).thenReturn("serialized"); String actual = Serializers.serialize(serializer, "arg", UTF8); assertEquals("serialized", actual); }
@Test public void shouldSerializeToStringUsingInterfaceDefaultMethodIfNotStringSerializer() throws Exception { Serializer serializer = mock(Serializer.class); ByteArrayOutputStream mockByteArrayOutputStream = mock(ByteArrayOutputStream.class); whenNew(ByteArrayOutputStream.class).withNoArguments().thenReturn(mockByteArrayOutputStream); when(mockByteArrayOutputStream.toByteArray()).thenReturn(SOME_STRING_UTF8_BYTES); String actual = Serializers.serialize(serializer, "arg", UTF8); assertEquals(SOME_STRING, actual); verify(serializer).serialize("arg", UTF8, mockByteArrayOutputStream); }