views:

166

answers:

1

In order to get good test coverage, I want to test the WriteExternal and ReadExternal methods of IPortableObject (as described at Creating an IPortableObject Implementation (.NET) ).

Here is code similar to what I have in my test method (which I like, and it works).

Person person = new Person { Name = "John Doe" };
Person personCopy = CoherenceTestHelper.CopyUsingPofSerialization<Person>(person);
Assert.AreEqual(person, personCopy);

But to get this to work, I had do subclass PofStreamWriter to override BeginProperty and PofStreamReader to override AdvanceTo. To me this smells a little funny, but I couldn't come up with a better solution. Below is my actual code for my CoherenceTestHelper.

Question: Has anybody else unit tested their IPortableObject implementation a better way?

public static class CoherenceTestHelper
{
    public static T CopyUsingPofSerialization<T>(T ipoIn) where T : IPortableObject, new()
    {
        T ipoOut = new T();

        IPofContext context = new SimplePofContext();
        using (MemoryStream ms = new MemoryStream())
        {
        IPofWriter writer = new MyPofStreamWriter(new DataWriter(ms), context);
        ipoIn.WriteExternal(writer);

        ms.Seek(0, 0);
        IPofReader reader = new MyPofStreamReader(new DataReader(ms), context);
        ipoOut.ReadExternal(reader);
        }

        return ipoOut;
    }

    private class MyPofStreamWriter : PofStreamWriter
    {
        public MyPofStreamWriter(DataWriter writer, IPofContext context)
        : base(writer, context)
        {
        }

        protected override void BeginProperty(int index)
        {
        }
    }

    private class MyPofStreamReader : PofStreamReader
    {
        public MyPofStreamReader(DataReader reader, IPofContext context)
        : base(reader, context)
        {
        }

        protected override bool AdvanceTo(int index)
        {
        return true;
        }
    }
}
A: 

This test is too concerned with the actual execution of the IPofReader and IPofWriter. I suggest you create a mock of the reader/writer using a framework like Rhino Mocks. Pass your POF method(s) the mocked reader/writer. Then simply assert that the read/write methods were called with the correct parameters.

Anthony Mastrean
Then I would need a specific mock for each IPortableObject implementation, where this helper can be used against any object. Also, I want to make sure the calls (e.g. ReadString and WriteString) are balanced and in the same order, which I'm not sure how to mock. I am concered with the actual execution.
Kevin Hakanson