我目前正在对复制功能进行一些单元测试,我需要比较旧列表和新复制列表之间的对象元素。 它工作正常,但我想知道我是否可以以不涉及for循环的方式来完成它。 这是我的目标:
new NaturePointObject
{
SId = 1,
Name = "Test",
Category = NaturePointCategory.Category1,
CreatorType = CreatorTypeEnum.1,
NaturR = NaturR.Bn,
Description = "Test",
Kumulation = Kumulation.EnEjendom,
Id = 1
}
我的旧列表包含" NaturePointObject"并被称为naturPointList,它将被复制到名为newNaturePointList的列表中。 以下是我如何知道它是否成功复制:
Assert.AreEqual(naturPointList.Count,newNaturePointList.Count);
for (var i = 0; i < newNatureList.Count; i++)
{
Assert.AreEqual(naturPointList[i].Category, newNaturePointList[i].Category);
Assert.AreEqual(naturPointList[i].Description, newNaturePointList[i].Description);
Assert.AreEqual(naturPointList[i].Kumulation, newNaturePointList[i].Kumulation);
Assert.AreEqual(naturPointList[i].Name, newNaturePointList[i].Name);
Assert.AreEqual(naturPointList[i].CreatorType, newNaturePointList[i].CreatorType);
Assert.AreEqual(naturPointList[i].NaturR, newNaturePointList[i].NaturR);
Assert.AreNotEqual(naturPointList[i].SId, newNaturePointList[i].SId);
}
正如您所看到的,并非对象的所有元素都必须相等。而且我不在乎&#34; Id&#34;对象。
有没有比运行for循环更短的方法呢?
答案 0 :(得分:1)
可能您想使用CollectionAssert.AreEqual(naturPointList, newNaturePointList, NaturePointObject.CategoryCreatorTypeComparer);
:
IComparer
您唯一需要注意的是,您需要实施Assert
,以便在public class NaturePointObject
{
private static readonly Comparer<NaturePointObject> CategoryCreatorTypeComparerInstance = new CategoryCreatorTypeRelationalComparer();
private sealed class CategoryCreatorTypeRelationalComparer : Comparer<NaturePointObject>
{
public override int Compare(NaturePointObject x, NaturePointObject y)
{
// compare fields which makes sense
if (ReferenceEquals(x, y)) return 0;
if (ReferenceEquals(null, y)) return 1;
if (ReferenceEquals(null, x)) return -1;
var categoryComparison = string.Compare(x.Category, y.Category, StringComparison.Ordinal);
if (categoryComparison != 0) return categoryComparison;
return string.Compare(x.CreatorType, y.CreatorType, StringComparison.Ordinal);
}
}
public static Comparer<NaturePointObject> CategoryCreatorTypeComparer
{
get
{
return CategoryCreatorTypeComparerInstance;
}
}
public int SId { get; set; }
public string Category { get; set; }
//other properties
public string CreatorType { get; set; }
}
方法中使用:
select * from
sysobjects, syscomments
WHERE sysobjects.id = syscomments.id and type='tr'
and text like '%AFTER UPDATE%'
答案 1 :(得分:0)
你可以尝试
Assert.IsTrue(naturPointList.SequenceEqual(newNaturePointList));
如果你想忽略Id,你可以创建其他类(没有ID)。
稍后编辑:您可以覆盖Equals方法并忽略Id。