Collections 是否可以在IEnumerable上使用Microsoft.VisualStudio.QualityTools.UnitTesting.CollectionAssert<;T>;?

Collections 是否可以在IEnumerable上使用Microsoft.VisualStudio.QualityTools.UnitTesting.CollectionAssert<;T>;?,collections,ienumerable,mstest,icollection,Collections,Ienumerable,Mstest,Icollection,我有一个测试场景,我想检查两个集合是否相等。我找到了类Microsoft.VisualStudio.QualityTools.UnitTesting.CollectionAssert,但它只适用于ICollection。由于我正在测试实体框架的存储库,因此需要比较IObjectSets,这是不行的-IObjectSet没有实现ICollection 是否有任何方法可以使用这个类来比较集合,或者我必须创建自己的实现?(为什么微软团队没有让这个类使用IEnumerable,因为这是集合的“基本接口”

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

是否有任何方法可以使用这个类来比较集合,或者我必须创建自己的实现?(为什么微软团队没有让这个类使用
IEnumerable
,因为这是集合的“基本接口”)

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

// 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(expected.ToList(), actual.ToList()); // but tidier...
//排列
var fakeContext=new FakeObjectContext();
var dummies=fakeContext.dummies;
var回购=新的外汇储备(伪造背景);
//表演
var result=repo.GetAll();
//断言
IsNotNull(结果,NullErrorMessage(MethodName(“GetAll”));
Assert.IsInstanceOfType(result,typeof(IEnumerable),IncorrectTypeMessage(MethodName(“GetAll”),typeof(IEnumerable));
集合assert.arequal(dummies.ToList(),result.ToList());
最后一行的
CollectionAssert.AreEqual
调用失败,说明索引0处的元素不相等。我做错了什么?

一个厚颜无耻的选择(虽然没有那么多信息)是断言
预期。SequenceEqual(实际)
返回
true

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

// 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(expected.ToList(), actual.ToList()); // but tidier...

如果要比较结果集,可能需要使用忽略顺序的结果集。您还应该确保对正在比较的元素类型实现了Equals。

使用
.ToList()
调用所有我的集合,代码将编译。但是,我无法编写一个我可以通过的测试-请参阅我在文章编辑中提供的代码。事实证明,在
dummeyentity上实现
.Equals()
成功了。我确实希望断言关注顺序,但在集合上实现
.Equals()
并调用
.ToList()
(无论如何,我都必须这样做才能使用
CollectionAssert.AreEquivalent
,这就是为什么他得到了代表,而不是你)成功了。谢谢!