【发布时间】:2011-05-11 12:32:26
【问题描述】:
我正在尝试将 Moq 添加到我在 MSTest 中的测试中以测试我的部分代码。
我要测试的代码是一段代码,它应该过滤服务检索的数据并通过它。我的代码是通过 MVP 模式设置的,并且我有以下组件。 (我正在测试我的演示者)
Service -> 该服务正在检索对象列表并将其放入模型中(我使用 Mock (Moq) 来返回值)
模型 -> 具有一些通用属性和文档列表的实体对象
View -> 我的用户控件实现的与演示者对话的界面。这个视图也被 moq 模拟了。
Presenter -> 对象从服务中检索模型并将此模型分配给视图的属性。
在我的第一个工作场景中,我只是从服务中检索模型,然后演示者将其传递给视图的属性。
//Setup AccountsPayableService Mock
_mockedDocumentService = new Mock<IDocumentService>();
DocumentModel<InvoiceDocumentRow> model = new DocumentModel<InvoiceDocumentRow>();
List<InvoiceDocumentRow> invoices = new List<InvoiceDocumentRow>();
InvoiceDocumentRow row = new InvoiceDocumentRow();
row.BillingMonth = DateTime.Now;
invoices.Add(row);
model.Documents = invoices;
_mockedDocumentService.Setup(service => service.GetInvoiceDocumentList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), _user)).Returns(model);
//Setup View Mock
_mockedView = new Mock<IInvoicesView>();
//Setup Presenter to be tested
_presenter = new FooPresenter(_mockedDocumentService.Object);
_presenter.SetView(_mockedView.Object);
//Act
//These events will make the presenter do the call to the service and assign this to the view property
_mockedView.Raise(view => view.Init += null, new EventArgs());
_mockedView.Raise(view => view.FirstLoad += null, new EventArgs());
//Assert
_mockedDocumentService.Verify(aps => aps.GetInvoiceDocumentList(from, changedTo, _user), Times.Once());
_mockedView.VerifySet(view => view.DocumentList = model);
此测试运行良好。
但是,我也有一个案例,演示者应该过滤从服务返回的一些结果,并将一个子集分配给视图。由于某种原因,我无法让它工作。
本质上,这是完全相同的测试代码,只是在演示器上使用了不同的方法,该方法从服务中检索数据、过滤数据,然后将其传递回视图。
当我像以前一样对视图属性进行断言时:
_mockedView.VerifySet(view => view.DocumentList.Documents = filteredModel.Documents);
我收到一个错误:
System.ArgumentException: Expression is not a property setter invocation.
我做错了什么?
【问题讨论】:
-
首先,一个建议。考虑开始使用控制反转。像 Ninject 这样的框架就是这样做的:code.google.com/p/ninject。更多内容:davidhayden.com/blog/dave/archive/2008/06/25/…
-
我们正在使用控制反转。只是暂时没有在我们的测试中使用任何框架。
标签: c# asp.net unit-testing tdd moq