Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I build this Expression with Moq without getting a method group error?

I need to run an expression on a given collection to determine if the expression in the code is written correctly. For the sake of the example, I am going to leave out some unnecessary context, but if anyone needs it, just comment and I'll edit the question and add whatever you need.

Let's say I have the following:

public interface IRepository
{
    IQueryable<T> Query<T>(Expression<Func<T, bool>> expression);
}

public class Repository : IRepository
{
    public IQueryable<T> Query<T>(Expression<Func<T, bool>> expression)
    {
        return _session.Query<T>(expression);
    }
}

and I want to write a spec like the following:

internal class when_executing_some_query : given_some_repository_context
{
    Establish context = () => 
    {
         IQueryable<SomeObject> objects = new List<SomeObject>
         {
             SomeObject1,
             SomeObject2,
             SomeObject3,
         }.AsQueryable();

         _expectedList = new List<SomeObject>
         {
             SomeObject1,
             SomeObject2,
         };

         MockedRepository.Setup(x => x.Query<SomeObject>(Moq.It.IsAny<Expression<Func<SomeObject, bool>>>)
             .Callback<Expression<Func<SomeObject, bool>>>(expression => _actualExpression = expression);
    }

    Because of = () => _actualList = objects.Select(_actualExpression).ToList();

    It should_execute_on_queryable_and_return_the_expected_items = () => //compare _expectedList with _actualList
}

However, I'm getting build errors on Moq.It.IsAny<Expression<Func<SomeObject, bool>>> saying

The best overloaded method match for 'Project.Domain.IRepository.Query(System.Linq.Expressions.Expression>)' has some invalid arguments

and

Argument 1: cannot convert from 'method group' to
'System.Linq.Expressions.Expression>'`

like image 519
David Sulpy Avatar asked Dec 24 '12 19:12

David Sulpy


2 Answers

To fix errors like this you need to invoke the method, not pass it as an argument. Just change your call from:

Moq.It.IsAny<Expression<Func<SomeObject, bool>>>

to:

Moq.It.IsAny<Expression<Func<SomeObject, bool>>>()

Note the parentheses.

like image 115
Chris Missal Avatar answered Sep 25 '22 01:09

Chris Missal


Based on this answer, it looks like you need () afterwards, e.g. It.IsAny<Expression<Func<SomeObject, bool>>>()

like image 20
Daryn Avatar answered Sep 23 '22 01:09

Daryn