Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/291.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何使用Moq用lambda表达式模拟服务调用_C#_Lambda_Mocking_Moq - Fatal编程技术网

C# 如何使用Moq用lambda表达式模拟服务调用

C# 如何使用Moq用lambda表达式模拟服务调用,c#,lambda,mocking,moq,C#,Lambda,Mocking,Moq,我使用Moq来模拟一个方法,该方法将lambda表达式作为可选参数并调用数据库 这是我试图嘲弄的真正方法 public IQueryable<T> AllSearchBy<T>(params Expression<Func<T, bool>>[] search) where T : class { IQueryable<T> result = _context.Set<T>(); f

我使用Moq来模拟一个方法,该方法将lambda表达式作为可选参数并调用数据库

这是我试图嘲弄的真正方法

public IQueryable<T> AllSearchBy<T>(params Expression<Func<T, bool>>[] search) where T : class
    {
        IQueryable<T> result = _context.Set<T>();

        foreach (var item in search)
        {
            result = result.Where(item);
        }

        return result;
    }

快速查看代码表明AllSearchBy需要一个表达式数组,但您的设置指定了一个表达式

也许试试这样的

模拟存储库 .Setupm=>m.AllSearchByIt.IsAny .Returnspredicates=>谓词 总数的 rateEndHsbSlcTable, source,predicate=>source.Wherepredicate.Compile.AsQueryable;
这成功了!我不得不稍微弄乱一下语法。非常感谢。
var mockRepository = new Mock<IRepository>();

var rateEndHsbSlcTable = new List<Rate_End_HSB_SLC>
        {
            new Rate_End_HSB_SLC
            {
                Limit = 10000,
                DwellingAgeMin = 0,
                DwelilngAgeMax = 25,
                Premium = 22M
            },
            new Rate_End_HSB_SLC
            {
                Limit = 10000,
                DwellingAgeMin = 26,
                DwelilngAgeMax = 50,
                Premium = 45M
            }
        };

mockRepository.Setup(m => m.AllSearchBy(It.IsAny<Expression<Func<Rate_End_HSB_SLC, bool>>>()))
                      .Returns((Expression<Func<Rate_End_HSB_SLC, bool>> predicate) => rateEndHsbSlcTable.Where(predicate.Compile()).AsQueryable());



IRateServices rateService = new RateServices(mockRepository.Object, new HelperServices(mockRepository.Object));
var test = _repository.AllSearchBy<Rate_End_HSB_SLC>(x => x.Limit == 10000 && x.DwellingAgeMin <= 19 && x.DwelilngAgeMax >= 19);
mockRepository.Setup(m => m.AllSearchBy(It.IsAny<Expression<Func<Rate_End_HSB_SLC, bool>>[]>()))
                      .Returns((Expression<Func<Rate_End_HSB_SLC, bool>>[] predicates) => predicates.Aggregate(rateEndHsbSlcTable, (source, predicate) => source.Where(predicate.Compile()).ToList()).AsQueryable());