OK so I'm fairly new to unit testing and everything is going well until now. I'm simplifying my problem here, but basically I have the following:
[Test]
public void ListTest()
{
var expected = new List<MyClass>();
expected.Add(new MyOtherClass());
var actual = new List<MyClass>();
actual.Add(new MyOtherClass());
Assert.AreEqual(expected,actual);
//CollectionAssert.AreEqual(expected,actual);
}
But the test is failing, shouldn't the test pass? what am I missing?
If you can't modify a class then this example can be helpful:
If you're comparing two lists, you should use test using collection constraints.
Also, in your classes, you will need to override the Equals method, otherwise like gleng stated, the items in the list are still going to be compared based on reference.
Simple override example:
A very simple way to get this test to work is to only create the
MyOtherClass
instance once. That way, when comparing the item in the two lists they will be "equal" (because they reference the same object). If you do this,CollectionAssert
will work just fine.If you don't this though, you'll need to implement
IEquatable<MyOtherClass>
inMyOtherClass
or overrideEquals
to define what makes two instances of that class the "same".Try to be a bit more specific about what you are trying to achieve. Explicitly telling that you want to compare entire sequence will solve the problem. I personally wouldn't rely on NUnit fancy features for determining what you meant by says AreEqual. E.g.
I convert my comment to answer on request.
Well, this fails because
AreEqual
uses reference comparison. In order to make it work you need value comparison(your own custom comparison).You can pretty much do that by implementing IEquatable interface. and keep in mind when you're implementing this interface you must override
Object.Equals
andObject.GetHashCode
as well to get consistent results..Net framework supports doing this without implementing
IEquatable
you need IEqualityComparer that should do the trick, butnunit
should have a method which takes this as a overload. Am not certain about "nunit" though.From Nunit documentation:
You have a list of objects ... so it's not the same as comparing 2 ints. What you should do is probably compare all the objects inside the list ... (Try converting your list to an array ... might actually work :) )
As I said (and most others as well), you'll probably need to override Equals. Here's MSDN page about how to do it (Covers Equals, == operator, and GetHashCode).
Similar with more info : [compare-equality-between-two-objects-in-nunit]
(Compare equality between two objects in NUnit)