posts - 94, comments - 124, trackbacks - 82

My Links

News

View Anthony Trudeau's profile on LinkedIn

Add to Technorati Favorites

Article Categories

Archives

Post Categories

Image Galleries

Other Links

Sunday, January 04, 2009

Unit testing for serialization

I'm created a simple utility class for unit testing serialization for my first post of the year.  I originally created the class to test data contract serialization, but I extended it for IFormatter based serializers for another class I needed to test.  I hope it proves useful.

You'll need the following using statements:

using System;

using System.IO;

using System.Runtime.Serialization;


The following utility class will help you with unit testing serialization for your data contracts and serialization using a standard IFormatter:

internal static class SerializationHelper

{

    public static string SerializeDataContract<T>(T testObject) where T: class

    {

        string fileName = Path.GetTempFileName();

 

        using (FileStream stream = new FileStream(fileName, FileMode.OpenOrCreate))

        {

            DataContractSerializer serializer =
                new DataContractSerializer(typeof(T));

            serializer.WriteObject(stream, testObject);

        }

 

        return fileName;

    }

 

    public static string SerializeObject<TObject, TFormatter>(TObject testObject)

        where TObject : class

        where TFormatter : IFormatter

    {

        string fileName = Path.GetTempFileName();

 

        using (FileStream stream = new FileStream(fileName, FileMode.OpenOrCreate))

        {

            IFormatter serializer = Activator.CreateInstance<TFormatter>();

            serializer.Serialize(stream, testObject);

        }

 

        return fileName;

    }

 

    public static T DeserializeDataContract<T>(string fileName) where T : class

    {

        using (FileStream stream = new FileStream(fileName, FileMode.Open))

        {

            DataContractSerializer serializer =
                new DataContractSerializer(typeof(T));

            return (serializer.ReadObject(stream) as T);

        }

    }

 

    public static TObject DeserializeObject<TObject, TFormatter>(string fileName)

        where TObject : class

        where TFormatter : IFormatter

    {

        using (FileStream stream = new FileStream(fileName, FileMode.Open))

        {

            IFormatter serializer = Activator.CreateInstance<TFormatter>();

            return (serializer.Deserialize(stream) as TObject);

        }

    }

}


The following is a sample of how you can use the utility class to test a data contract based class (source and target are both objects of the same data contract type):

string serializedFile = SerializationHelper.SerializeDataContract(source);

target = SerializationHelper

    .DeserializeDataContract<WorkflowRequest>(serializedFile);

posted @ Sunday, January 04, 2009 4:54 PM | Feedback (1) | Filed Under [ .NET ]

Powered by: