使用 Moq.ItIs<expression tree>()

问题描述 投票:0回答:1

我不知道如何使用 Moq.ItIs<>

传递表达式树

参数类型为Expression>

但我不明白为什么我不能通过这样的东西 Moq.ItIs>>(d=>d.Property == "test")

我收到错误“ 错误 CS1061“Expression>”不包含“Enable”的定义,并且找不到接受“Expression>”类型的第一个参数的可访问扩展方法“Enable”(您是否缺少 using 指令或程序集引用? ) ...\MockRepositories\GenericMock.cs 484 活动 ”

DestinationRepository
              .Setup(x => x.GetAsync(
It.Is<Expression<Func<Destination, bool>>>(d=>d.Enable), It.IsAny<Func<IQueryable<Destination>,IOrderedQueryable<Destination>>>(),
It.Is<string>(x => x == Constants.IncludeParentDestinationInfo),
It.IsAny<int>(),
It.IsAny<int>(),
It.IsAny<bool>()))
             .Returns(Task.FromResult(DestinationStub.DestinationsParentInfo))
             .Verifiable();

Task<IEnumerable<TEntity>> GetAsync(Expression<Func<TEntity, bool>>? whereCondition = null,
                                            Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>>? orderBy = null,
                                            string includeProperties = "",
                                            int startRecord = -1,
                                            int pageSize = -1,
                                            bool forceSingleQuery = false);

我不知道如何传递第一个参数 whereCondition 的表达式树。

我之前尝试创建表达式树

表达式> expr = d => d.Enable;

        DestinationRepository
          .Setup(x => x.GetAsync(It.Is<Expression<Func<Destination, bool>>>(expr), It.IsAny<Func<IQueryable<Destination>,
                                     IOrderedQueryable<Destination>>>(), It.Is<string>(x => x == Constants.IncludeParentDestinationInfo), It.IsAny<int>(), It.IsAny<int>(), It.IsAny<bool>()))
         .Returns(Task.FromResult(DestinationStub.DestinationsParentInfo))
         .Verifiable();
c# moq repository-pattern expression-trees
1个回答
0
投票

有点不清楚您想通过使用

It.Is
实现什么目的,但我假设您希望模拟仅在使用表达式
GetAsync
专门调用
d => d.Enable
时返回一个值。

如果是这样,您可以在不使用

It.Is
的情况下执行此操作(对于您的
includeProperties
参数也类似):

DestinationRepository
    .Setup(x => x.GetAsync(
        d => d.Enable, // <--
        It.IsAny<Func<IQueryable<Destination>, IOrderedQueryable<Destination>>>(),
        Constants.IncludeParentDestinationInfo, // <--
        It.IsAny<int>(),
        It.IsAny<int>(),
        It.IsAny<bool>()
    ))
    .Returns(Task.FromResult(DestinationStub.DestinationsParentInfo))
    .Verifiable();
© www.soinside.com 2019 - 2024. All rights reserved.