views:

132

answers:

3

I'm working on a DAL method that uses an ORDER BY clause in a SELECT. The return value from the method is an IEnumerable<T>, where T is a class that encapsulates a domain entity, and the sort order would be based on one of the properties of this class, namely, "Priority." It's important that this ORDER BY works, of course, so I want to write a sort verification into the unit test for this method. Does anyone have a quick and simple algorithm for testing the order of an IEnumerable<T> based on one of the properties of T? Is there something LINQ-y that I can use?

var items = repository.GetItems(true);   //true tells it to use the ORDER BY
items.ToList().ForEach(i => Assert.IsTrue(??What happens here??));

Thanks in advance.

A: 

You could do another OrderBy and then compare the results.

Daniel A. White
+1  A: 

How about:

var list = items.ToList();
for(int i = 1; i < list.Count; i++) {
    Assert.IsTrue(yourComparer.Compare(list[i - 1], list[i]) <= 0);
}

where yourComparer is an instance of YourComparer which implements IComparer<YourBusinessObject>. This ensures that every element is less than the next element in the enumeration.

Jason
A: 

Something LINQ-y would be to use a separate sorted query...

var sorted = from item in items
 orderby item.Priority
 select item;

Assert.IsTrue(items.SequenceEquals(sorted));

Type inference means you'd need a

 where T : IHasPriority

However, if you have multiple items of the same priority, then for a unit test assertion you're probably best off just looping with the list index as Jason suggested.

Tanzelax