2009-01-07 30 views
50

您好我是新来的TDD和的xUnit,所以我想测试我的方法是这样的:xUnit:断言两个列表<T>是否相等?

List<T> DeleteElements<T>(this List<T> a, List<T> b); 
当然,这不是真正的方法:) 的

有没有我可以使用任何断言方法?我认为这样会很好

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); 

有没有这样的事情?

回答

59

xUnit.Net识别集合,所以你只需要做

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

你可以看到其他可用的集合断言在CollectionAsserts.cs

对于NUnit的图书馆藏书比较方法是

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

and

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

更多细节在这里:CollectionAssert

MbUnit的也有类似NUnit的集合断言:Assert.Collections.cs

+1

源代码链接已修改http://xunit.codeplex.com/SourceControl/changeset/view/d947e347c5c3#Samples%2fAssertExamples%2fCollectionExample.cs – 2010-09-07 12:26:35

+1

评论中的新链接也被打破。 – 2013-02-23 17:46:38

27

在的xUnit的当前版本(1.5),你可以只使用

Assert.Equal(预计,实际);

上面的方法将通过两个列表的元素比较来做一个元素。 我不确定这是否适用于任何以前的版本。

6

有了xUnit,如果你想樱桃挑选每个元素的属性来测试你可以使用Assert.Collection。

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

这测试预期的计数并确保每个操作都被验证。