无法为通用的 ienumerable 任务设置最小起订量模拟

Cant setup mock with moq for generic ienumerable task

我正在使用模拟库 Moq,但我无法为此签名设置模拟:

Task<IEnumerable<TEntity>> GetAllAsync<TEntity>(
            Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
            string includeProperties = null,
            int? skip = null,
            int? take = null)
            where TEntity : class, IEntity;
}

单元测试class

using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using ICEBookshop.API.Factories;
using ICEBookshop.API.Interfaces;
using ICEBookshop.API.Models;
using Moq;
using SpecsFor;

namespace ICEBookshop.API.UnitTests.Factories
{
    public class GivenCreatingListOfProducts : SpecsFor<ProductFactory>
    {
        private Mock<IGenericRepository> _genericRepositorMock;

        protected override void Given()
        {
            _genericRepositorMock = new Mock<IGenericRepository>();
        }

        public class GivenRepositoryHasDataAndListOfProductsExist : GivenCreatingListOfProducts
        {
            protected override void Given()
            {
                _genericRepositorMock.Setup(
                        expr => expr.GetAllAsync<Product>(It.IsAny<Func<IQueryable<Product>>>(), null, null, null))
                    .ReturnsAsync<Product>(new List<Product>());

            }
        }
    }
}

这行代码快把我逼疯了:

genericRepositorMock.Setup(
                        expr => expr.GetAllAsync<Product>(It.IsAny<Func<IQueryable<Product>>>(), null, null, null))
                    .ReturnsAsync<Product>(new List<Product>());

问题是我不知道如何设置 GetAllAsync 所以它会编译并且会 return 一个产品列表。所需的行为是它 return 是一个产品列表。

谁能帮我用这个签名设置模拟?

首先,提供的初始示例具有 orderBy 参数作为

Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy

但是在设置中有

It.IsAny<Func<IQueryable<Product>>>()

与接口定义不匹配,导致编译错误。

其次,使用 It.IsAny<> 作为可选参数,以允许模拟方法在执行测试时具有灵活性。

下面的简单例子演示

[TestMethod]
public async Task DummyTest() {
    //Arrange
    var mock = new Mock<IGenericRepository>();
    var expected = new List<Product>() { new Product() };
    mock.Setup(_ => _.GetAllAsync<Product>(
         It.IsAny<Func<IQueryable<Product>, IOrderedQueryable<Product>>>(),
         It.IsAny<string>(),
         It.IsAny<int?>(),
         It.IsAny<int?>()
        )).ReturnsAsync(expected);

    var repository = mock.Object;

    //Act
    var actual = await repository.GetAllAsync<Product>(); //<--optional parameters excluded

    //Assert
    CollectionAssert.AreEqual(expected, actual.ToList());
}