c# – 添加一个Where()表达式的Mock IRavenQueryable

前端之家收集整理的这篇文章主要介绍了c# – 添加一个Where()表达式的Mock IRavenQueryable前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在为一个新的mvc3项目做一些基本的概念验证类型代码.我们正在使用Moq与RavenDB.

行动:

public ActionResult Index(string id)
{
    var model = DocumentSession.Query<FinancialTransaction>()
        .Where(f => f.ResponsibleBusinessId == id);
    return View(model);
}

测试:

private readonly Fixture _fixture = new Fixture();

[Test]
public void Index_Action_Returns_List_Of_FinancialTransactions_For_Business([Random(0,50,5)]int numberOfTransactionsToCreate)
{
    // Arrange
    var session = new Mock<IDocumentSession>();
    var financialController = new FinancialController { DocumentSession = session.Object };

    var businessId = _fixture.CreateAnonymous<string>();
    var transactions = _fixture.Build<FinancialTransaction>()
        .With(f => f.ResponsibleBusinessId,businessId)
        .CreateMany(numberOfTransactionsToCreate);

    // Mock
    var ravenQueryableMock = new Mock<IRavenQueryable<FinancialTransaction>>();
    ravenQueryableMock.Setup(x => x.GetEnumerator()).Returns(transactions.GetEnumerator);
    ravenQueryableMock.Setup(x => x.Customize(It.IsAny<Action<Object>>()).GetEnumerator()).Returns(() => transactions.GetEnumerator());

    session.Setup(s => s.Query<FinancialTransaction>()).Returns(ravenQueryableMock.Object).Verifiable(); 

    // Act
    var actual = financialController.Index(businessId) as ViewResult;

    // Assert
    Assert.IsNotNull(actual);
    Assert.That(actual.Model,Is.InstanceOf<List<FinancialTransaction>>());

    var result = actual.Model as List<FinancialTransaction>;
    Assert.That(result.Count,Is.EqualTo(numberOfTransactionsToCreate));
    session.VerifyAll();
}

这将出现在.Where(f => f.ResponsibleBusinessId == id)中的问题.从讽刺的IRavenQueryable,我返回一个FinancialTransactions列表,所以人们会认为.Where()将基于此过滤.但是由于它是IQueryable,我猜测它正在枚举的时候一直执行这个表达式.

要验证,我将操作的查询更改为:

var model = DocumentSession.Query<FinancialTransaction>()
    .ToList()
    .Where(f => f.ResponsibleBusinessId == id);

这样做让测试通过,但是它并不理想,因为这意味着它会枚举所有的记录,然后过滤它们.

有没有办法让Moq与此协同工作?

解决方法

评论中所述,您不应该在测试中嘲笑RavenDB API.

RavenDB对单元测试有极好的支持,感谢InMemory模式:

[Test]
public void MyTest()
{
    using (var documentStore = new EmbeddableDocumentStore { RunInMemory = true })
    {
        documentStore.Initialize();

        using (var session = documentStore.OpenSession())
        {
            // test
        }
    }
}
原文链接:https://www.f2er.com/csharp/94877.html

猜你在找的C#相关文章