Moq Returns with multiple Linq Expressions

白昼怎懂夜的黑 提交于 2019-12-20 05:31:32

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/35565353/moq-returns-with-multiple-linq-expressions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!