开发者

Is it possible to use Microsoft.VisualStudio.QualityTools.UnitTesting.CollectionAssert on an IEnumerable<T>?

开发者 https://www.devze.com 2022-12-16 12:07 出处:网络
I have a testing scenario where I want to check if two collections are equal. I have found the class Microsoft.VisualStudio.QualityTools.UnitTesting.CollectionAssert, but it only works on ICollection&

I have a testing scenario where I want to check if two collections are equal. I have found the class Microsoft.VisualStudio.QualityTools.UnitTesting.CollectionAssert, but it only works on ICollection<开发者_Python百科;T>. Since I'm testing a repository for Entity Framework, and thus need to compare IObjectSet<T>s, that won't do - IObjectSet<T> doesn't implement ICollection<T>.

Is there any way I can use this class to compare the collecitons, or do I have to create my own implementation? (And why the heck didn't the Microsoft team make the class work with IEnumerable<T> instead, as that is the "base interface" for collections?)

EDIT: This is my test code:

// 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());

The CollectionAssert.AreEqual call on the last line fails, stating that the elements at index 0 are not equal. What am I doing wrong?


A cheeky option (not quite as much info though) is to assert that expected.SequenceEqual(actual) returns true.

You could write a wrapper method that forces a collection (.ToList() on each)? But to be honest you might as well just call .ToList() in the unit test code:

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


If you're comparing result sets you might want to use CollectionAssert.AreEquivalent which will ignore the order. You should also make sure you have implemented Equals on the type of elements you are comparing.

0

精彩评论

暂无评论...
验证码 换一张
取 消