proteus proteus - 2 months ago 28
C# Question

comparing two lists with Xunit

I'm using xunit to unit test, I have a list of expected objects and a list of actual objects. How do I compare a specific element of each object (a date) in both lists to see if they are equal? I've found the Assert.Collection method but I can't figure out how it can compare the contents of two lists.

Answer Source

You do not need XUnit specifics. This problem can be solved by using LINQ.

To compare an element from the list simply use:

Assert.True(isList[1] == shouldList[1]);

Just access the lists content directly. If you do not know the index, you can use LINQ:

Assert.True(shouldList.Any(x => x == isList[1]);

This will check if the shouldList contains any element equal to the second element in isList.

If you want to compare if the lists content is identical, without knowing the sequence, use something like this:

Assert.True(shouldList.All(shouldItem => isList.Any(isItem => isItem == shouldItem)));

This checks for all items in shouldList that at least one item in isList is identical.

REMARK:

I used the == operator for comparing. If this works depends on the list's content. You said you are comparing dates, here the equals will check for equality, not identity. For most reference types the equals will only compare identity. Here you have either to overwrite the default equals implementation or to compare custom fields and properties instead of using the == operator.