How to setup a Moq method to return IOrderedQueryable
Join the DZone community and get the full member experience.
Join For FreeHere’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.
Comments