yegor256
yegor256

Reputation: 105073

How to validate object serialization mechanism?

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 string
    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?

Upvotes: 1

Views: 1343

Answers (3)

Peter Tillemans
Peter Tillemans

Reputation: 35341

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.

Upvotes: 0

Nikita Rybak
Nikita Rybak

Reputation: 68006

Replace

String written = out.toString();

with

byte[] written = out.toByteArray();

You can't store random binary data as String. String is for text.

Upvotes: 5

Tom Hawtin - tackline
Tom Hawtin - tackline

Reputation: 147164

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.

Upvotes: 3

Related Questions