为了获得良好的测试覆盖率,我想测试(如创建 IPortableObject 实现 (.NET)WriteExternal
中所述)的和ReadExternal
方法。IPortableObject
这是类似于我的测试方法中的代码(我喜欢它,并且它有效)。
Person person = new Person { Name = "John Doe" };
Person personCopy = CoherenceTestHelper.CopyUsingPofSerialization<Person>(person);
Assert.AreEqual(person, personCopy);
但是为了让它工作,我必须做子类PofStreamWriter
来覆盖BeginProperty
和PofStreamReader
覆盖AdvanceTo
。对我来说,这闻起来有点好笑,但我想不出更好的解决方案。下面是我的 CoherenceTestHelper 的实际代码。
问题:是否有其他人IPortableObject
以更好的方式对他们的实现进行了单元测试?
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;
}
}
}