是否可以在IEnumerable <t>上使用Microsoft.VisualStudio.QualityTools.UnitTesting.CollectionAssert?</t>

时间:2010-01-13 17:16:59

标签: collections ienumerable mstest icollection

我有一个测试场景,我想检查两个集合是否相等。我找到了课程Microsoft.VisualStudio.QualityTools.UnitTesting.CollectionAssert,但它仅适用于ICollection<T>。由于我正在测试实体框架的存储库,因此需要比较IObjectSet<T> s,这不会 - IObjectSet<T>没有实现ICollection<T>

有什么方法可以用这个类来比较集合,还是我必须创建自己的实现? (为什么微软团队没有让这个类与IEnumerable<T>一起使用,因为那是集合的“基础接口”?)

编辑:这是我的测试代码:

// Arrange
var fakeContext = new FakeObjectContext();
var dummies = fakeContext.Dummies;
var repo = new EFRepository<DummyEntity>(fakeContext);

// Act
var result = repo.GetAll();

// Assert
Assert.IsNotNull(result, NullErrorMessage(MethodName("GetAll")));
Assert.IsInstanceOfType(result, typeof(IEnumerable<DummyEntity>), IncorrectTypeMessage(MethodName("GetAll"), typeof(IEnumerable<DummyEntity>)));
CollectionAssert.AreEqual(dummies.ToList(), result.ToList());

最后一行的CollectionAssert.AreEqual调用失败,指出索引0处的元素不相等。我做错了什么?

2 个答案:

答案 0 :(得分:3)

一个厚颜无耻的选择(虽然信息不多)是断言expected.SequenceEqual(actual)返回true

您可以编写一个强制集合的包装器方法(每个.ToList())?但说实话,您也可以在单元测试代码中调用.ToList()

CollectionAssert.AreEqual(expected.ToList(), actual.ToList()); // but tidier...

答案 1 :(得分:2)

如果您要比较结果集,可能需要使用忽略订单的CollectionAssert.AreEquivalent。您还应确保已对要比较的元素类型实施了等式。