xUnit : Assert two List are equal?

2019-01-17 09:05发布

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

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

of course that's not the real method :) 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 ?

标签: xunit.net
3条回答
贪生不怕死
2楼-- · 2019-01-17 09:50

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

查看更多
太酷不给撩
3楼-- · 2019-01-17 09:50

With xUnit, should you want to cherry pick properties of each element to test you can use Assert.Collection.

Assert.Collection(elements, 
  elem1 => Assert.Equal(expect1, elem1.SomeProperty),
  elem2 => { 
     Assert.Equal(expect2, elem2.SomeProperty);
     Assert.True(elem2.TrueProperty);
  });

This tests the expected count and ensures that each action is verified.

查看更多
放荡不羁爱自由
4楼-- · 2019-01-17 09:51

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.

查看更多
登录 后发表回答