Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NUnit comparing two lists

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?

like image 413
SOfanatic Avatar asked Nov 08 '13 14:11

SOfanatic


People also ask

How do I compare two objects in NUnit?

Just install ExpectedObjects from Nuget, you can easily compare two objects's property value, each object value of collection, two composed object's value and partial compare property value by anonymous type. Reference: ExpectedObjects github. Introduction of ExpectedObjects.

Is equal NUnit?

NUnit is able to compare single-dimensioned arrays, multi-dimensioned arrays, nested arrays (arrays of arrays) and collections. Two arrays or collections are considered equal if they have the same dimensions and if each pair of corresponding elements is equal.

What is Assert areequal?

Tests whether the specified objects are equal and throws an exception if the two objects are not equal. Different numeric types are treated as unequal even if the logical values are equal.

What is assert in NUnit?

Assertions are central to unit testing in any of the xUnit frameworks, and NUnit is no exception. NUnit provides a rich set of assertions as static methods of the Assert class. If an assertion fails, the method call does not return and an error is reported.


1 Answers

If you're comparing two lists, you should use test using collection constraints.

Assert.That(actual, Is.EquivalentTo(expected)); 

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:

public class Example {     public int ID { get; set; }      public override bool Equals(object obj)     {         return this.ID == (obj as Example).ID;     } } 
like image 188
matth Avatar answered Oct 01 '22 23:10

matth