user1244893
user1244893

Reputation: 105

Moq Returns with multiple Linq Expressions

I have the following method within a repository that I am trying to Mock:

IEnumerable<TEntity> GetAll(
      Expression<Func<TEntity, bool>> filter = null,
      Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
      string includeProperties = "")

I've setup the following:

mockContactNumberRepository.Setup(x => x.GetAll(
    It.IsAny<Expression<Func<ContactNumber, bool>>>(), 
    It.IsAny<Func<IQueryable<ContactNumber>, IOrderedQueryable<ContactNumber>>>(),
    It.IsAny<string>()))
    .Returns(new Func<Expression<Func<ContactNumber, bool>>, 
        IQueryable<ContactNumber>>(ex => _contactNumbers.Where(ex.Compile()).AsQueryable()));

When running the unit test I receive an error message about Parameter count mismatch. I understand this is because the Returns is only specifying the first parameter but I am unsure how to specify the further parameters.

I've found many questions that ask similar questions but not found one with multiple lambda expressions.

Any help you can give would be much appreciated.

Upvotes: 1

Views: 1342

Answers (1)

Jason Boyd
Jason Boyd

Reputation: 7029

Your GetAll method takes three arguments and returns an IEnumerable<TEntity>. The valueFunction parameter in Returns needs to have a matching signature and return type. The valueFunction parameter in your example only has two input arguments and the second argument does not match any of the argument types passed to GetAll. It should look something like this (I don't have the benefit of the compiler checking my syntax but I think what I have here should be correct):

mockContactNumberRepository
.Setup(x => 
    x
    .GetAll(
        It.IsAny<Expression<Func<ContactNumber, bool>>>(), 
        It.IsAny<Func<IQueryable<ContactNumber>, IOrderedQueryable<ContactNumber>>>(),
        It.IsAny<string>()))
.Returns(new Func<
    Expression<Func<ContactNumber, bool>>, 
    Func<IQueryable<ContactNumber>, IOrderedQueryable<ContactNumber>>,
    string,
    IEnumerable<TEntity>>((arg1, arg2, arg3) => 
        {
            // arg1 is Expression<Func<ContactNumber, bool>>
            // arg2 is Func<IQueryable<ContactNumber>, IOrderedQueryable<ContactNumber>>
            // arg3 is string
            // Do something here and return an IEnumerable<TEntity>
        }));

Upvotes: 1

Related Questions