我正在为一个新的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与此协同工作?