After discovering some pretty significant serializaton issues in the code base, and approximately 0% testing of the implementation of ISerializable, I've been spending the last couple of days writing tests for the serialization... I've been using the following code to do the serialization, easy to use:
MyObject m = new MyObject("Test");
Assert.IsTrue( m.Equals( Serialization.SerializeAndDeserialize( m ) ) );
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
/// <summary>Class to aid the serialization / deserialization of objects in unit tests.</summary>
public static class Serialization
{
/// <summary>Serializes and deserializes the specified object.</summary>
/// <typeparam name="T">The type of object to serialize / deserialize.</typeparam>
/// <param name="toSerialize">The actual object to serialize / deserialize.</param>
/// <param name="filename">The location to serialize the object to.</param>
/// <returns>The deserialized object.</returns>
public static T SerializeAndDeserialize<T>( T toSerialize, string filename )
{
// Serialization
using(Stream sStream = new FileStream( filename, FileMode.Create ))
new BinaryFormatter().Serialize( sStream, toSerialize );
// Deserialization
T newObj;
using(Stream dStream = new FileStream( filename, FileMode.Open ))
newObj = (T) new BinaryFormatter().Deserialize( dStream );
//Delete files
File.Delete( filename );
return newObj;
}
}