|
Tuesday, 02 August 2011 15:20 |
The code below contains utility methods and an example test method to check if a class is truly serializable by cloning it using serialization then comparing the original to the clone.
public static Stream Serialize(object source)
{
IFormatter formatter = new BinaryFormatter();
Stream stream = new MemoryStream();
formatter.Serialize(stream, source);
return stream;
}
public static T Deserialize(Stream stream)
{
IFormatter formatter = new BinaryFormatter();
stream.Position = 0;
return (T)formatter.Deserialize(stream);
}
public static T CloneBySerialization(T source)
{
return Deserialize(Serialize(source));
}
public static void AssertRoundTripSerializationIsPossible(T source)
{ // assumes T implements Equals
T clone = CloneBySerialization(source);
Assert.AreEqual(source, clone, "Failed round-trip serialization, clone not equal to source");
Assert.IsFalse(ReferenceEquals(source, clone), "Failed round-trip serialization, clone points to souce");
}
[TestMethod]
public void ClassShouldBeSeralizable()
{
Foo original = new Foo("bar");
AssertRoundTripSerializationIsPossible(original);
}
 Read more: |