Testing Serialization

I tested this method to be sure that it would work:

[Test()]
public void TestLoadingAndSavingFile()
{
    TaskCollection collection = new TaskCollection();
    Task task = new Task("Wash Car", "Auto");
    task.Attributes.Add(new MetadataAttribute("IsReoccurring", false));
    collection.Add(task);

    task = new Task("Wax Car", "Auto");
    task.Attributes.Add(new MetadataAttribute("IsReoccurring", true));
    task.Attributes.Add(new MetadataAttribute("ReoccurrenceUnit", 180));
    task.Attributes.Add(new MetadataAttribute("ReoccurrenceMeasurement", "days"));
    collection.Add(task);

    Assert.AreEqual(2, collection.Count);

    //Serialize the file
    serialization.SaveToXmlFile(collection, PATH);

    XmlDocument document = new XmlDocument();
    document.Load(PATH);

    Assert.IsNotNull(document.DocumentElement);
    Assert.AreEqual(2, document.DocumentElement.ChildNodes.Count);

    MetadataElementCollection<Task> tasksCollection = serialization.LoadFromXmlFile(PATH);
    Assert.IsNotNull(tasksCollection);
    Assert.AreEqual(2, tasksCollection.Count);

    TaskCollection tasksOfficialCollection = new TaskCollection();
    tasksOfficialCollection.CopyFrom(tasksCollection);

    Assert.AreEqual(2, tasksOfficialCollection.Count);
}

There are a few things to note; I create a collection of tasks, then save it to a file.  I want to make sure that file is valid, and so I save it to a file, and check it out with an XML document object.  Next, I load it, to ensure I can get it back, and check it.  The last step is to ensure that I can get it back to a TaskCollection, and not of the base class type.

This was a problem, as without copying the items to the right collection, I wasn't able to convert the reference.  So I had to create a CopyFrom method to copy the items in the collection to the new collection.  It looks like this:

public void CopyFrom(MetadataElementCollection<Task> collection)
{
    foreach (Task item in collection)
        this.Add(item);
}

This worked pretty well in the test.

Comments

No Comments