Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

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]publicvoidShouldAssertSimpleOrder(){// Arrangevarnumbers=new[]{4,2,5,1};// Actvarascending=numbers.OrderBy(x=>x).ToArray();vardescending=numbers.OrderByDescending(x=>x).ToArray();// AssertExpect(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 ofComparer.Default which relies on theIComparable<T> interface, meaning means that:

  1. a lot of types arealready supported
  2. you could implementIComparable<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]publicvoidShouldAssertOrderedAscending(){// Arrangevardoggos=new[]{new{id=1,name="Rex",adopted=newDateTime(2020,1,1)},new{id=2,name="Spot",adopted=newDateTime(2019,5,6)},new{id=3,name="Woofles",adopted=newDateTime(2020,4,5)}};Expect(doggos.Select(d=>d.id)).To.Be.Ordered.Ascending();// ActvarorderedByAdoption=doggos.OrderBy(d=>d.adopted);// AssertExpect(orderedByAdoption.Select(d=>d.adopted)).To.Be.Ordered.Ascending();}

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

Happy testing!

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Code monkey extraordinaire
  • Location
    Durban
  • Work
    Full stack dev at Codeo
  • Joined

More fromDavyd McColl

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp