Mocking classes that implement IQueryable with Moq(使用 Moq 实现 IQueryable 的模拟类)
问题描述
我花了一个晚上试图模拟一个实现 IQueryable 的对象:
I spent an evening trying to mock an object that implements IQueryable:
public interface IRepo<T> : IQueryable<T>
{
}
我能想到的最好的方法是这样的:
The best I could come up with is something like this:
var items = new Item[] {}.AsQueryable();
var repo = new Mock<IRepo>();
repo.Setup(r => r.GetEnumerator()).Returns(items.GetEnumerator());
repo.Setup(r => r.Provider).Returns(items.Provider);
repo.Setup(r => r.ElementType).Returns(items.ElementType);
repo.Setup(r => r.Expression).Returns(items.Expression);
有没有更简洁的方法来做同样的事情?在 IRepo 中公开一个返回 IQueryable 的属性/方法会更容易,并且像这样简单地模拟:
Is there a more concise way to do the same? It would be easier to expose a property/method in IRepo that returns IQueryable and the simply mock like this:
repo.Setup(r => r.GetItems()).Returns(new Items[]{ }.AsQueryable());
但这不是我想做的=)
推荐答案
这并不是什么新鲜事,只是一种更简洁的方式.我也有存储库,其中存储库本身也是 IQueryable,所以我需要同样的东西.我基本上只是在我的测试项目的根级别将您的代码放入这样的扩展方法中,以使其可用于所有测试:
This is nothing new, just a cleaner way of doing it. I also have repositories where the repository itself is also an IQueryable, so I needed the same thing. I basically just put your code into an extension method like this at the root level of my test project, to make it available to all tests:
public static class MockExtensions
{
public static void SetupIQueryable<T>(this Mock<T> mock, IQueryable queryable)
where T: class, IQueryable
{
mock.Setup(r => r.GetEnumerator()).Returns(queryable.GetEnumerator());
mock.Setup(r => r.Provider).Returns(queryable.Provider);
mock.Setup(r => r.ElementType).Returns(queryable.ElementType);
mock.Setup(r => r.Expression).Returns(queryable.Expression);
}
}
这基本上只是提供了可重用性,因为您可能希望在多个测试中执行此操作,并且在每个测试中它都使意图清晰且混乱最小化.:)
This basically just offers reusability, since you're likely to want to do this in several tests, and in each test it makes the intention clear and the mess minimal. :)
这篇关于使用 Moq 实现 IQueryable 的模拟类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 Moq 实现 IQueryable 的模拟类


- 如何用自己压缩一个 IEnumerable 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- 输入按键事件处理程序 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01