views:

172

answers:

2

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?

+2  A: 

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...
Marc Gravell
With `.ToList()` calls on all my collections, the code compiles. However, I am unable to write a test I can pass - see the code I provided in an edit to my post.
Tomas Lycken
Turns out implementing `.Equals()` on `DummyEntity` did the trick.
Tomas Lycken
+2  A: 

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.

Lee
I actually do want the assertion to care about order, but implementing `.Equals()` in combination with calling `.ToList()` on the collections (which I would have had to do anyway to use `CollectionAssert.AreEquivalent`, which is why he got the rep and not you) did the trick. Thanks!
Tomas Lycken