如何检查是否名单是有序? [英] How to check if a list is ordered?

查看:106
本文介绍了如何检查是否名单是有序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做的一些单元测试,我想知道是否有任何的方式来测试,如果名单是由它包含的对象的属性进行排序。

现在我做这种方式,但我不喜欢,我希望有一个更好的办法。有人可以帮我吗?

  //(填充列表)
清单< StudyFeedItem> studyFeeds =
    Feeds.GetStudyFeeds(2120,DateTime.Today.AddDays(-200),20);StudyFeedItem previous = studyFeeds.First();的foreach(在studyFeeds StudyFeedItem项)
{
    如果(项目!= previous)
    {
        Assert.IsTrue(previous.Date> item.Date);
    }    previous =项目;
}


解决方案

如果你正在使用MSTest的,你可能想看看<一个href=\"http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.unittesting.collectionassert.areequal.aspx\">CollectionAssert.AreEqual.

Enumerable.SequenceEqual 的可能只有一个断言使用其他有用的API。

在这两种情况下,你应该prepare保存在预期的顺序预期列表中的列表,然后该列表进行比较的结果。

下面是一个例子:

  VAR studyFeeds = Feeds.GetStudyFeeds(2120,DateTime.Today.AddDays(-200),20);
VAR expectedList = studyFeeds.OrderByDescending(X =&GT; x.Date);
Assert.IsTrue(expectedList.SequenceEqual(studyFeeds));

I am doing some unit tests and I want to know if there's any way to test if a list is ordered by a property of the objects it contains.

Right now I am doing it this way but I don't like it, I want a better way. Can somebody help me please?

// (fill the list)
List<StudyFeedItem> studyFeeds = 
    Feeds.GetStudyFeeds(2120, DateTime.Today.AddDays(-200), 20);   

StudyFeedItem previous = studyFeeds.First();

foreach (StudyFeedItem item in studyFeeds)
{
    if (item != previous)
    {
        Assert.IsTrue(previous.Date > item.Date);
    }

    previous = item;
}

解决方案

If you are using MSTest, you may want to take a look at CollectionAssert.AreEqual.

Enumerable.SequenceEqual may be another useful API to use in an assertion.

In both cases you should prepare a list that holds the expected list in the expected order, and then compare that list to the result.

Here's an example:

var studyFeeds = Feeds.GetStudyFeeds(2120, DateTime.Today.AddDays(-200), 20);   
var expectedList = studyFeeds.OrderByDescending(x => x.Date);
Assert.IsTrue(expectedList.SequenceEqual(studyFeeds));

这篇关于如何检查是否名单是有序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆