开发者

Moq - Mock Generic Repository

开发者 https://www.devze.com 2023-01-26 22:25 出处:网络
I have a Generic repository and are trying to cast the .Returns to a Expression but it refuse... My code is following:

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 tak开发者_高级运维e 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());

}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号