【发布时间】:2010-08-13 10:00:26
【问题描述】:
在单元测试中(在 Visual Studio 2008 中)我想将一个大对象的内容(准确地说是自定义类型的列表)与该对象的存储引用进行比较。目标是确保以后对代码的任何重构都会产生相同的对象内容。
废弃的想法: 第一个想法是序列化为 XML,然后比较硬编码的字符串或文件内容。这将允许轻松发现任何差异。但是,由于我的类型在没有 hack 的情况下无法进行 XML 序列化,因此我必须找到另一种解决方案。我可以使用二进制序列化,但这将不再可读。
有没有简单而优雅的解决方案?
编辑:根据 Marc Gravell 的建议,我现在这样做:
using (MemoryStream stream = new MemoryStream())
{
//create actual graph using only comparable properties
List<NavigationResult> comparableActual = (from item in sparsed
select new NavigationResult
{
Direction = item.Direction,
/*...*/
VersionIndication = item.VersionIndication
}).ToList();
(new BinaryFormatter()).Serialize(stream, comparableActual);
string base64encodedActual = System.Convert.ToBase64String(stream.GetBuffer(), 0, (int)stream.Length);//base64 encoded binary representation of this
string base64encodedReference = @"AAEAAAD....";//this reference is the expected value
Assert.AreEqual(base64encodedReference, base64encodedActual, "The comparable part of the sparsed set is not equal to the reference.");
}
本质上,我确实首先选择了可比较的属性,然后对图形进行编码,然后将其与类似编码的参考进行比较。 编码可以以简单的方式进行深度比较。我使用 base64 编码的原因是,我可以轻松地将引用存储在字符串变量中。
【问题讨论】:
-
序列化的想法对于深度图来说确实不错。
-
序列化并不完全可靠。你可能会得到假阴性。见stackoverflow.com/questions/2244223/…
标签: c# visual-studio unit-testing object comparison