Over a million developers have joined DZone.

How to setup a Moq method to return IOrderedQueryable

DZone's Guide to

How to setup a Moq method to return IOrderedQueryable

· ·
Free Resource

Here’s something that stumped me for a while today. I’ve got the following Linq query in my repository (this is using the ORM from DevExpress, XPO, but the basic idea is the same)

internal virtual IOrderedQueryable GetMyData(string keyVal)
return (from MyEntity ent in new XPQuery(Context)
where ent.Key == keyVal
orderby ent.SortCol
select end);

The problem I was having was in mocking the return value from this method. One cannot create an interface so I could not create a list of items to return from the mocked method.

I finally hit on this magic combination of linq queries that lets me return a set built by hand for the mock.

var emptyLst = new List();
var lst = (from d in emptyLst select d).AsQueryable().OrderBy(x => x.Key );
_mockRepo.Setup(r => r.MyMockedEvent).Returns(lst);

This seems to work like a charm


Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}