
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:
- a lot of types arealready supported
- you could implement
IComparable<T>
on your complex type and be able to order it anywhere with LINQ - 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)
For further actions, you may consider blocking this person and/orreporting abuse