I'm trying to validate that my custom Java object is serialized/de-serialized properly, and I can use this serialization mechanism with files, streams, etc. This is the test I created. Is it a correct approach?
public class SerializableTest {
@Test public void shouldSerialize() throws Exception {
Foo foo = new Foo(123);
// serialize it to a s开发者_Go百科tring
ByteArrayOutputStream out = new ByteArrayOutputStream();
new ObjectOutputStream(out).writeObject(foo);
String written = out.toString();
// read it back
ByteArrayInputStream in = new ByteArrayInputStream(written.getBytes());
Foo foo2 = (Foo)(new ObjectInputStream(in).readObject());
// check that two objects are identical
assertEquals(foo, foo2);
}
}
What is wrong here?
Replace
String written = out.toString();
with
byte[] written = out.toByteArray();
You can't store random binary data as String. String is for text.
You are attempting to decode binary data to text and then encode back to binary. Always a bad idea.
You should also flush decorator output streams.
Nothing, as long as Foo has a proper equals implementation.
I would not pass it through the String transformation as this is evil as the other also remarked already.
精彩评论