Serialization { public static void serialize(Object object, Path file) throws SerializationException { try (final OutputStream os = Files.newOutputStream(file, WRITE, CREATE_NEW)) { serialize(object, os); } catch (IOException e) { throw new SerializationException("Serialization failed", e); } } private  Serialization(); static void serialize(Object object, Path file); static void serialize(Object object, OutputStream outputStream); static byte[] serialize(Object object); static T deserialize(Path filePath); @SuppressWarnings("unchecked") static T deserialize(InputStream inputStream); @SuppressWarnings("unchecked") static T deserialize(byte[] bytes); static T requireSerializable(T o, String name);  }
@Test public void shouldProvideDetailedDebugInformationOnNotSerializableException() throws ReflectiveOperationException { class Quux {} class Baz implements Serializable { final Quux quux = new Quux(); } class Bar implements Serializable { final Baz baz = new Baz(); } class Foo implements Serializable { final Bar bar = new Bar(); } final Foo foo = new Foo(); final Fn<Foo> fn = () -> foo; try { Serialization.serialize(fn); } catch (SerializationException e) { assertThat(e.getCause(), instanceOf(NotSerializableException.class)); assertThat(e.getCause().toString(), is( "java.io.NotSerializableException: com.spotify.flo.SerializationTest$1Quux\n" + "\t- field (class \"com.spotify.flo.SerializationTest$1Baz\", name: \"quux\", type: \"class com.spotify.flo.SerializationTest$1Quux\")\n" + "\t- object (class \"com.spotify.flo.SerializationTest$1Baz\", com.spotify.flo.SerializationTest$1Baz@" + Integer.toHexString(System.identityHashCode(foo.bar.baz)) + ")\n" + "\t- field (class \"com.spotify.flo.SerializationTest$1Bar\", name: \"baz\", type: \"class com.spotify.flo.SerializationTest$1Baz\")\n" + "\t- object (class \"com.spotify.flo.SerializationTest$1Bar\", com.spotify.flo.SerializationTest$1Bar@" + Integer.toHexString(System.identityHashCode(foo.bar)) + ")\n" + "\t- field (class \"com.spotify.flo.SerializationTest$1Foo\", name: \"bar\", type: \"class com.spotify.flo.SerializationTest$1Bar\")\n" + "\t- object (class \"com.spotify.flo.SerializationTest$1Foo\", com.spotify.flo.SerializationTest$1Foo@" + Integer.toHexString(System.identityHashCode(foo)) + ")\n" + "\t- element of array (index: 0)\n" + "\t- array (class \"[Ljava.lang.Object;\", size: 1)\n" + "\t- field (class \"java.lang.invoke.SerializedLambda\", name: \"capturedArgs\", type: \"class [Ljava.lang.Object;\")\n" + "\t- root object (class \"java.lang.invoke.SerializedLambda\", " + serializedLambda(fn) + ")")); } }
@Test public void serializeShouldPropagateSerializationExceptions() throws SerializationException { exception.expect(SerializationException.class); Serialization.serialize(new Object()); }
@Test public void serializeShouldPropagateIOException() throws Exception { exception.expect(SerializationException.class); Serialization.serialize("foobar", Paths.get("non-existent-dir", "file")); }