Thursday 17 July 2008

NUnit Serialization Test

NUnit test that verifies that your class is fully serializable and desializable:

[Test]
public void SerializationTest()
{
 MyGenericCollection myCollection = new MyGenericCollection();
 SerializationHelper.SerializeNow(myCollection);
 myCollection = (MyGenericCollection)SerializationHelper.DeSerializeNow();
}


internal class SerializationHelper
{
  private static readonly string DefaultFilePath = "test.dat";

  internal static void SerializeNow(object c)
  {
    SerializeNow(c, DefaultFilePath);
  }

  internal static void SerializeNow(object c, string filepath)
  {
   FileInfo f = new FileInfo(filepath);
   using (Stream s = f.Open(FileMode.Create))
   {
      BinaryFormatter b = new BinaryFormatter();
    b.Serialize(s, c);
   }
  }

  internal static object DeSerializeNow()
  {
    return DeSerializeNow(DefaultFilePath);
  }

  internal static object DeSerializeNow(string filepath)
  {
    FileInfo f = new FileInfo(filepath);
    using (Stream s = f.Open(FileMode.Open))
    {
      BinaryFormatter b = new BinaryFormatter();
      return b.Deserialize(s);
    }
  }
}

No comments: