Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

xUnit : Assert two List<T> are equal?

Tags:

c#

xunit

I'm new to TDD and xUnit so I want to test my method that looks something like:

List<T> DeleteElements<T>(this List<T> a, List<T> b); 

Is there any Assert method that I can use ? I think something like this would be nice

List<int> values = new List<int>() { 1, 2, 3 }; List<int> expected = new List<int>() { 1 }; List<int> actual = values.DeleteElements(new List<int>() { 2, 3 });  Assert.Exact(expected, actual); 

Is there something like this ?

like image 880
Petar Petrov Avatar asked Jan 07 '09 09:01

Petar Petrov


People also ask

How do you assert two objects are equal in xUnit?

You'll have to implement IEquatable<T> for your objects, and then Assert. Equals will work. Assert. Same() compares by reference; it asserts that Obj1 and Obj2 are the same object rather than just looking the same.

What is assert in xUnit?

In xUnit and many other testing frameworks, assertion is the mean that we conduct our test. In other word we assert an expectation that something is true about a piece of code. There are many different types of assertion in xUnit that we can use.

Which attribute is used to mark a method as test method in xUnit?

Testing a positive case This method is decorated with the Fact attribute, which tells xUnit that this is a test.


2 Answers

2021-Apr-01 update

I recommend using FluentAssertions. It has a vast IntelliSense-friendly assertion library for many use cases including collections

collection.Should().Equal(1, 2, 5, 8); collection.Should().NotEqual(8, 2, 3, 5); collection.Should().BeEquivalentTo(8, 2, 1, 5); 

Original answer

xUnit.Net recognizes collections so you just need to do

Assert.Equal(expected, actual); // Order is important 

You can see other available collection assertions in CollectionAsserts.cs

For NUnit library collection comparison methods are

CollectionAssert.AreEqual(IEnumerable, IEnumerable) // For sequences, order matters 

and

CollectionAssert.AreEquivalent(IEnumerable, IEnumerable) // For sets, order doesn't matter 

More details here: CollectionAssert

MbUnit also has collection assertions similar to NUnit: Assert.Collections.cs

like image 154
Konstantin Spirin Avatar answered Oct 09 '22 17:10

Konstantin Spirin


In the current version of XUnit (1.5) you can just use

Assert.Equal(expected, actual);

The above method will do an element by element comparison of the two lists. I'm not sure if this works for any prior version.

like image 22
hwiechers Avatar answered Oct 09 '22 16:10

hwiechers