gpt4 book ai didi

c# - Moq - 模拟通用存储库

转载 作者:太空狗 更新时间:2023-10-30 01:26:44 26 4
gpt4 key购买 nike

我有一个通用存储库,正在尝试将 .Returns 转换为表达式,但它拒绝...我的代码如下:

public RepositoryTest()
{
IList<MockObjectSet> mocks = new List<MockObjectSet>()
{
new MockObjectSet { FirstName = "Beta", LastName = "Alpha", Mobile = 12345678 },
new MockObjectSet { FirstName = "Alpha", LastName = "Beta", Mobile = 87654321 }
};

var mockRepository = new Mock<IRepository<MockObjectSet>>();

mockRepository.Setup(x => x.GetBy(It.IsAny<Expression<Func<MockObjectSet, bool>>>()))
.Returns((Expression<Func<MockObjectSet, bool>> predicate) => mocks.Where(predicate).ToList());

}

只是说

Delegate System.Func<System.Collections.Generic.IEnumerable<expWEBCRM.Tests.Repositories.MockObjectSet>> does not take 1 arguments

提前致谢!

最佳答案

您需要像这样显式指定 Returns 重载的类型参数:

mockRepository.Setup(x => x.GetBy(It.IsAny<Expression<Func<MockObjectSet, bool>>>()))
.Returns<Expression<Func<MockObjectSet, bool>>>(predicate => mocks.Where(predicate).ToList());

编辑 存储库接受一个表达式并将其用于 IQueryable 。模拟数据源实际上是一个 IEnumerable 。 LINQ 接口(interface)的不同之处在于一个采用 lambda,一个采用表达式:

IQueryable<T>.Where(Expression<Func<T,bool>>);
IEnumerable<T>.Where(Func<T,bool>);

在这种情况下发生的事情是尝试用 IEnumerable.Where 调用 Expression<Func<T,bool>> 。解决此问题的最简单方法是将源集合设置为 IQueryable :

public RepositoryTest()
{
IQueryable<MockObjectSet> mocks = new List<MockObjectSet>()
{
new MockObjectSet { FirstName = "Beta", LastName = "Alpha", Mobile = 12345678 },
new MockObjectSet { FirstName = "Alpha", LastName = "Beta", Mobile = 87654321 }
}.AsQueryable();

var mockRepository = new Mock<IRepository<MockObjectSet>>();

mockRepository.Setup(x => x.GetBy(It.IsAny<Expression<Func<MockObjectSet, bool>>>()))
.Returns<Expression<Func<MockObjectSet, bool>>>(predicate => mocks.Where(predicate).ToList());

}

关于c# - Moq - 模拟通用存储库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4288523/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com