我正在尝试将Moq添加到我在MSTest中的测试中以测试我的部分代码。
我想测试哪些代码不起作用的代码是一段代码,它应该过滤服务检索到的数据并通过它。我的代码是通过MVP模式设置的,我有以下组件。 (我正在测试我的主持人)
服务 - >此服务正在检索对象列表并将其放入模型中(我使用Mock(Moq)返回值)
模型 - >具有一些常规属性和文档列表的实体对象
查看 - >我的usercontrol正在实现的接口与演示者交谈。这个观点也被moq嘲笑。
演示者 - > object从服务中检索模型并将此模型分配给视图的属性。
在我的第一个场景中工作,我只是从服务中检索一个模型,并且演示者将其传递给视图的属性。
//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.
我做错了什么?
答案 0 :(得分:0)
这不起作用,因为filteredModel.Documentos位于另一个上下文中。您的视图没有收到此信息,接收来自某种过滤方法的其他列表。
改变你的结构我会建议创建扩展方法,并明显地测试它们。
所以你可以简单地放list.FilterByName("Billy");
所以你会创建类似的东西:
public static IEnumerable<ObjectFromVdCruijsen> FilteredByNome(this IEnumerable<ObjectFromVdCruijsen> enumerable, string name){
if (!string.IsNullOrEmpty(name)){
enumerable = enumerable.Where(s => s.Name.ToUpperInvariant().Contains(name.ToUpperInvariant()));
}
return enumerable;
}
答案 1 :(得分:0)
我找到了解决自己问题的方法。
我将verifySet替换为正常断言_mockedviw.object,所以我使用存根来测试而不是模拟,这是完美的。使用我使用的存根功能:
_mockedView.SetupAllProperties();
默认情况下无法比较2个不同的参考对象,所以我只是手动检查属性。