2011-03-07 78 views
3

如何在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()); 
    } 

回答

7

创建一个硬编码在预期IEnumerable<string>与电影片名顺序,从结果集合中抽取标题并使用SequenceEqual检查它们是否以相同的顺序(假设您的引用常量为Movie对象,并且MovieTitle属性):

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

你可以在每个项目上断言就行了,如果你知道以期望:

Assert.IsTrue(results[0]== theres_something_about_mary) 
Assert.IsTrue(results[1]== the_ring) 
+0

'/(?!<=)=(?==)/ == /'。 – delnan 2011-03-07 10:34:38

+0

IEnumerable 没有索引器。 – alexn 2011-03-07 10:36:52

1

你可以使用的IEnumerable的SequenceEquals扩展方法,像这样:

Assert.IsTrue(results.SequenceEquals(new[] {"cars", "a_bugs_life"})); 
0

在这里,我已经使用了愉快的阅读中NUnit 2.4介绍Assert.That()语法。重要的一点是Is.EqualTo约束将强制参数的顺序。

[TestFixture] 
public class UnitTest 
{ 
    [Test] 
    public void SameOrder() // passes 
    { 
     IEnumerable<int> expected = new[] { 1, 9, 0, 4}; 
     IEnumerable<int> actual = new[] { 1, 9, 0, 4 }; 
     Assert.That(actual, Is.EqualTo(expected)); 
    } 

    [Test] 
    public void WrongOrder() // fails 
    { 
     IEnumerable<int> expected = new[] { 1, 9, 0, 4 }; 
     IEnumerable<int> actual = new[] { 9, 0, 1, 4 }; 
     Assert.That(actual, Is.EqualTo(expected)); 
    } 
} 
1

Assert.AreEqual(actual,expected);