Mocking Queryables

Recently, we’ve been mocking out IQueryable’s as return values, which had led to setups that look like the following…

programs.setup_result_for(x => x.All()).Return(new List<IProgram> {active_program,inactive_program}.AsQueryable());

I just switched over to the following syntax… by creating an extension method.

programs.setup_result_for(x => x.All()).will_return(active_program,inactive_program);

The following are the extensions methods to make this work.

public static IMethodOptions<IEnumerable<R>> will_return<R>(this IMethodOptions<IEnumerable<R>> options,
                                                            params R[] items)
{
    return options.Return(items);
}

public static IMethodOptions<IQueryable<R>> will_return<R>(this IMethodOptions<IQueryable<R>> options,
                                                           params R[] items)
{
    return options.Return(new Query<R>(items));
}

 

and…

 

internal class Query<T> : IQueryable<T>
{
    private readonly IQueryable<T> query;

    public Query(params T[] items)
    {
        query = items.AsQueryable();
    }

    public Expression Expression
    {
        get { return query.Expression; }
    }

    public Type ElementType
    {
        get { return query.ElementType; }
    }

    public IQueryProvider Provider
    {
        get { return query.Provider; }
    }

    public IEnumerator<T> GetEnumerator()
    {
        return query.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}

 

Hope, this helps!

Related Articles:

Post Footer automatically generated by Add Post Footer Plugin for wordpress.

About Mo Khan

mO, is just a kid who's excited about writing software. He's a student of his profession, and just wants to share his thoughts on software development.
This entry was posted in TDD. Bookmark the permalink. Follow any comments here with the RSS feed for this post.

One Response to Mocking Queryables

  1. I don’t get the point of the Query class.

    Isn’t it simpler to just do:

    return options.Return(items.AsQueryable());