c# - 断言集合的顺序正确

标签 c#

如何在 MSTest 中断言返回集合的顺序是正确的?

[TestMethod]
    public void when_sorting_movies_it_should_be_able_to_sort_all_movies_by_title_descending()
    {
        populateTestMovies(movie_collection);
        MovieLibrary movieLibrary = new MovieLibrary(movie_collection);
        IEnumerable<Movie> results = movieLibrary.sort_all_movies_by_title_descending();
        Assert.IsTrue(results.Contains(theres_something_about_mary));
        Assert.IsTrue(results.Contains(the_ring));
        Assert.IsTrue(results.Contains(shrek));
        Assert.IsTrue(results.Contains(pirates_of_the_carribean));
        Assert.IsTrue(results.Contains(indiana_jones_and_the_temple_of_doom));
        Assert.IsTrue(results.Contains(cars));
        Assert.IsTrue(results.Contains(a_bugs_life));
        Assert.AreEqual(7, results.Count());
    }

最佳答案

创建硬编码 IEnumerable<string>使用预期顺序的电影标题,从结果集合中提取标题并使用 SequenceEqual检查它们的顺序是否相同(假设您引用的常量是 Movie 对象,并且 Movie 具有 Title 属性):

IEnumerable<string> expected = new[] 
{ 
    theres_something_about_mary.Title, 
    the_ring.Title,
   /* and so on */ 
};
Assert.IsTrue(results.Select(m => m.Title).SequenceEqual(expected));

关于c# - 断言集合的顺序正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5218505/

相关文章:

c# - 在 DateTime 中存储超过 24 小时

c# - 如何在 Ubuntu Server 上的 Mono 中获得系统正常运行时间?

c# - 如何向当前服务器请求资源(相对路径)?

c# - asp.net mvc razor 中的可点击单选按钮文本

c# - Web Socket 消息未全部收到

c# - 最小起订量 'TestMethod(Action<int> callback)' 并能够 'call' 回调

c# - 在 VBScript 中使用 vb.net

c# - 计算不同的结果-方法 PointToScreen 获取桌面(屏幕)相关控件的点

c# - 从正在运行的进程中获取 DLL 名称,可能吗?

javascript - 如何从 C# 代码后面调用本地存储的 javascript 函数