DEV Community

Cover image for Asserting sequence order with NExpect
Davyd McColl
Davyd McColl

Posted on

Asserting sequence order with NExpect

I've made a recent small addition to NExpect core which I hope will make certain kinds of tests a little easier for everyone: tests where we have to ensure that the output of our system-under-test is ordered.

Some simple examples:

[Test]
public void ShouldAssertSimpleOrder()
{
    // Arrange
    var numbers = new[] { 4, 2, 5, 1 };

    // Act
    var ascending = numbers.OrderBy(x => x).ToArray();
    var descending = numbers.OrderByDescending(x => x).ToArray();

    // Assert
    Expect(ascending)
        .To.Be.Ordered.Ascending();
    Expect(descending)
        .To.Be.Ordered.Descending();
}

So you may be thinking: "this is all good and well, but what if I want to assert ordering on collections of types more complex than numbers?"

There are some strategies you can take there. First off, the underlying logic in the above assertions takes advantage of Comparer.Default which relies on the IComparable<T> interface, meaning means that:

  1. a lot of types are already supported
  2. you could implement IComparable<T> on your complex type and be able to order it anywhere with LINQ
  3. you can .Select off the interesting bit and assert on that

(3) is probably going to be your go-to, so here's an example:

[Test]
public void ShouldAssertOrderedAscending()
{
    // Arrange
    var doggos = new[]
    {
        new { id = 1, name = "Rex", adopted = new DateTime(2020, 1, 1) },
        new { id = 2, name = "Spot", adopted = new DateTime(2019, 5, 6) },
        new { id = 3, name = "Woofles", adopted = new DateTime(2020, 4, 5) }
    };
    Expect(doggos.Select(d => d.id))
        .To.Be.Ordered.Ascending();
    // Act
    var orderedByAdoption = doggos.OrderBy(d => d.adopted);
    // Assert
    Expect(orderedByAdoption.Select(d => d.adopted))
        .To.Be.Ordered.Ascending();
}

The above, and first-class support for IOrderedEnumerable<T> is added in NExpect 1.0.181.

Happy testing!

Top comments (0)