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;
}
}
}