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

StackOverflow https://stackoverflow.com/questions/2058745

Question

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<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?

Was it helpful?

Solution

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...

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top