Faking a repository - faking Find method
For my unit testing, I need to fake a Repository. I have easily been able to fake all the methods except for the Find method which takes in a Linq Expression de开发者_开发问答legate as a parameter.
My fake repository code is listed below (unnecessary code removed). The code I have tried using is shown in the Find method. The compiler error I get from VS is:
"System.Collections.Generic.List' does not contain a definition for 'Where' and the best extension method overload 'System.Linq.Queryable.Where(System.Linq.IQueryable, System.Linq.Expressions.Expression>)' has some invalid arguments"
Any ideas on how I bend the criteria parameter into the argument type required?
public class FakeCourseRepository : IRepository<Course>
{
private List<Course> courseList;
public FakeCourseRepository(List<Course> courses)
{
courseList = courses;
}
public IList<Course> Find(System.Linq.Expressions.Expression<Func<Course, bool>> criteria)
{
return courseList.Where<Course>(criteria);
}
}
Try changing
return courseList.Where<Course>(criteria);
to
return courseList.AsQueryable().Where<Course>(criteria).ToList();
You're trying to pass an Expression, normally used with IQueryables, into an overload of Where designed to work with IEnumerables and which takes a straight delegate. You're also returning an IQueryable when your method clearly says it gives back an IList. Whether you really need an IList, or if you can get away with a concrete List (which is also IEnumerable and IQueryable and thus allows for easier further manipulation) is a topic for another discussion, but understand that ILists, as ILists, cannot be iterated; you'll have to use or implement an AsEnumerable() method to convert it into an iterable format.
I would suggest using a mocking framework for unit testing repositories.
精彩评论