我正在模拟我的存储库接口(interface),但不确定如何设置采用表达式并返回对象的方法?我正在使用 Moq 和 NUnit。
接口(interface):
public interface IReadOnlyRepository : IDisposable
{
IQueryable<T> All<T>() where T : class;
T Single<T>(Expression<Func<T, bool>> expression) where T : class;
}
Test with IQueryable 已经设置好,但不知道如何设置 T Single:
private Moq.Mock<IReadOnlyRepository> _mockRepos;
private AdminController _controller;
[SetUp]
public void SetUp()
{
var allPages = new List<Page>();
for (var i = 0; i < 10; i++)
{
allPages.Add(new Page { Id = i, Title = "Page Title " + i, Slug = "Page-Title-" + i, Content = "Page " + i + " on page content." });
}
_mockRepos = new Moq.Mock<IReadOnlyRepository>();
_mockRepos.Setup(x => x.All<Page>()).Returns(allPages.AsQueryable());
//Not sure what to do here???
_mockRepos.Setup(x => x.Single<Page>()
//----
_controller = new AdminController(_mockRepos.Object);
}
最佳答案
你可以这样设置:
_mockRepos.Setup(x => x.Single<Page>(It.IsAny<Expression<Func<Page, bool>>>()))//.Returns etc...;
但是,您遇到了 Moq 的一个缺点。你会想在那里放一个实际的表达式而不是使用 It.IsAny
,但 Moq 不支持设置采用特定表达式的表达式的方法(这是一个难以实现的功能)。困难在于必须弄清楚两个表达式是否等价。
所以在你的测试中你可以传入任何 Expression<Func<Page,bool>>
它会传回你设置的模拟返回的任何内容。测试的值(value)被稀释了一点。
关于c# - Moq.Mock<T> - 如何设置采用表达式的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2751935/