Pau*_*aul 29 c# nunit unit-testing moq
我正在模拟我的存储库接口,我不知道如何设置一个接受表达式并返回一个对象的方法?我正在使用Moq和NUnit
接口:
public interface IReadOnlyRepository : IDisposable
{
    IQueryable<T> All<T>() where T : class;
    T Single<T>(Expression<Func<T, bool>> expression) where T : class;
}
使用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);
}
Jas*_*yon 41
您可以这样设置:
_mockRepos.Setup(x => x.Single<Page>(It.IsAny<Expression<Func<Page, bool>>>()))//.Returns etc...;
然而,你遇到了Moq的一个缺点.您可能希望在其中放置实际表达式而不是使用It.IsAny,但Moq不支持设置采用特定表达式的表达式的方法(这是一个难以实现的特性).难点在于必须弄清楚两个表达式是否相同.
因此,在您的测试中,您可以传入任何内容 Expression<Func<Page,bool>>,它将传回您设置模拟返回的任何内容.测试的价值有点稀释.   
让.Returns调用对allPages变量返回表达式的结果.
_mockRepos.Setup(x => x.Single<Page>(It.IsAny<Expression<Func<Page, bool>>>()))
    .Returns( (Expression<Func<Page, bool>> predicate) => allPages.Where(predicate) );
| 归档时间: | 
 | 
| 查看次数: | 21927 次 | 
| 最近记录: |