Unit testing classes that implement IXmlSerializable

I have seen unit tests that test serialization by writing to the file system and, though it serves the same purpose, I am not a huge fan of having to have FileSystem permissions applied to my unit testing framework unless I am intentionally trying to write something to the filesystem in my application. So, here is a unit test template I have used to test a class’ implementation of IXmlSerializable.

 
[Test]
public void ReadReturnsEquatableObjectToObjectWritten() {
    MemoryStream stream = new MemoryStream();
    IXmlSerializable xmlSerializableObject = new MyXmlSerializableObject();
    //Set values on the xmlSerializableObject
    IXmlSerializable deserializedXmlSerializableObject = new MyXmlSerializableObject();
    using (XmlWriter writer = new XmlTextWriter(stream, Encoding.UTF8)) {
        xmlSerializableObject.WriteXml(writer);
        stream.Seek(0, SeekOrigin.Begin);
        using (XmlReader reader = XmlReader.Create(stream)) {
            deserializedXmlSerializableObject.ReadXml(reader);
        }
    }
    //Assert values on deserialized object are as expected.
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s