带有多个Linq表达式的Moq返回 [英] Moq Returns with multiple Linq Expressions

查看:49
本文介绍了带有多个Linq表达式的Moq返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要模拟的存储库中有以下方法:

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

运行单元测试时,我收到有关参数计数不匹配的错误消息.我了解这是因为Returns仅指定第一个参数,但是我不确定如何指定其他参数.

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.

我发现了很多类似的问题,但没有找到具有多个lambda表达式的问题.

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.

推荐答案

您的GetAll方法采用三个参数并返回IEnumerable<TEntity>. Returns中的valueFunction参数需要具有匹配的签名和返回类型.您的示例中的valueFunction参数只有两个输入参数,第二个参数与传递给GetAll的任何参数类型都不匹配.它应该看起来像这样(我没有编译器检查语法的好处,但我认为这里的内容应该是正确的):

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

这篇关于带有多个Linq表达式的Moq返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆