cat mocking-queryables.md

Mocking Queryables

Nov 04, 2008

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 classQuery<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();
   }
  }

I hope, this helps!