Make sure the collection is in the correct order.

How to assert in MSTest that the order of the returned collection is correct?

[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());
    }
+3
source share
6 answers

Create hard-coded IEnumerable<string>movies with the names in the expected order, pull the titles from the collection of results and use SequenceEqualto check that they are in the same order (assuming your mentioned Movieobject constants and that Moviehas a property 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));
+7
source

SequenceEquals IEnumerable, :

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

Assert.AreEqual(, );

+1

, , :

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

Here I used the nice-to-read syntax Assert.That()introduced in NUnit 2.4 . The important point is that the restriction Is.EqualTowill ensure the order of the parameters.

[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));
    }
}
0
source

All Articles