简体   繁体   中英

Moq - Mock Generic Repository

I have a Generic repository and are trying to cast the .Returns to a Expression but it refuse... My code is following:

public RepositoryTest()
{
    IList<MockObjectSet> mocks = new List<MockObjectSet>()
    {
        new MockObjectSet { FirstName = "Beta", LastName = "Alpha", Mobile = 12345678 },
        new MockObjectSet { FirstName = "Alpha", LastName = "Beta", Mobile = 87654321 }
    };

    var mockRepository = new Mock<IRepository<MockObjectSet>>();

    mockRepository.Setup(x => x.GetBy(It.IsAny<Expression<Func<MockObjectSet, bool>>>()))
        .Returns((Expression<Func<MockObjectSet, bool>> predicate) => mocks.Where(predicate).ToList());

}

It just say

Delegate System.Func<System.Collections.Generic.IEnumerable<expWEBCRM.Tests.Repositories.MockObjectSet>> does not take 1 arguments

Thanks in advance!

You need to explicitly specify the type parameters of the Returns overload like so:

mockRepository.Setup(x => x.GetBy(It.IsAny<Expression<Func<MockObjectSet, bool>>>()))
        .Returns<Expression<Func<MockObjectSet, bool>>>(predicate => mocks.Where(predicate).ToList());

EDIT The repository takes an expression and uses it on a IQueryable . The mock data source is actually an IEnumerable . The difference in the LINQ interface is one takes a lambda, the one an expression:

IQueryable<T>.Where(Expression<Func<T,bool>>);
IEnumerable<T>.Where(Func<T,bool>);

What happens in this scenario is trying to call IEnumerable.Where with Expression<Func<T,bool>> . The easiest way to fix this is to have the source collection as IQueryable :

public RepositoryTest()
{
    IQueryable<MockObjectSet> mocks = new List<MockObjectSet>()
    {
        new MockObjectSet { FirstName = "Beta", LastName = "Alpha", Mobile = 12345678 },
        new MockObjectSet { FirstName = "Alpha", LastName = "Beta", Mobile = 87654321 }
    }.AsQueryable();

    var mockRepository = new Mock<IRepository<MockObjectSet>>();

    mockRepository.Setup(x => x.GetBy(It.IsAny<Expression<Func<MockObjectSet, bool>>>()))
        .Returns<Expression<Func<MockObjectSet, bool>>>(predicate => mocks.Where(predicate).ToList());

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM