views:

1154

answers:

6

I am using C# 2.0 with Nunit Test. I have some object that needs to be serialized. These objects are quite complex (inheritance at different levels and contains a lot of objects, events and delegates).

How can I create a Unit Test to be sure that my object is safely serializable?

+2  A: 

I have this in some unit test here at job:

MyComplexObject dto = new MyComplexObject();
MemoryStream mem = new MemoryStream();
BinaryFormatter b = new BinaryFormatter();
try
{
    b.Serialize(mem, dto);
}
catch (Exception ex)
{
    Assert.Fail(ex.Message);
}

Might help you... maybe other method can be better but this one works well.

Daok
You need to be careful of NonSerialized (or transient in java) objects though, and those should be tested as part of your serialization and deserialization.
Egwor
+13  A: 

In addition to the test above - which makes sure the serializer will accept your object, you need to do a round-trip test. Deserialize the results back to a new object and make sure the two instances are equivalent.

Scott Weinstein
+3  A: 

serialize the object (to memory or disk), deserialize it, use reflection to compare the two, then run all of the unit tests for that object again (except serialization of course)

this assumes that your unit tests can accept an object as a target instead of making their own

Steven A. Lowe
+10  A: 

Here is a generic way:

public static Stream Serialize(object source)
{
    IFormatter formatter = new BinaryFormatter();
    Stream stream = new MemoryStream();
    formatter.Serialize(stream, source);
    return stream;
}

public static T Desiaralize<T>(Stream stream)
{
    IFormatter formatter = new BinaryFormatter();
    stream.Position = 0;
    return (T)formatter.Deserialize(stream);
}

public static T Clone<T>(object source)
{
    return Desiaralize<T>(Serialize(source));
}
GeverGever
works perfectly. Comparing the original to the Cloned copy is a great test of serialization as checking IsSerializable only checks the attribute of the class and not base class or other properties
Catch22
A: 

What if the source is null? I have a requirement where I just create a new object, do not set its fields. I want to find out if the fields of the object are serializable.