2011-05-11 64 views
1

我试图将Moq添加到MSTest中的测试中以测试我的代码的某些部分。使用Moq来验证对象内的列表是否正确更改

我想测试哪些代码不工作的代码是应该过滤服务所检索的数据并将其传递的代码片段。我的代码通过MVP模式设置,我有以下组件。 (我测试我的演讲)

  • 服务 - >此服务被检索对象的列表,并把这个模型中(我使用的是模拟(MOQ)返回值)

  • 模型 - >具有一些常规属性和文档列表的实体对象

  • 查看 - >我的用户控件正在实现的接口与演示者交谈。这个观点也被moq嘲笑。

  • Presenter - > 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

首先,一个建议。考虑开始使用控制反转。像Ninject这样的框架可以执行此操作:http://code.google.com/p/ninject/。更多信息:http://davidhayden.com/blog/dave/archive/2008/06/25/NinjectInlineModuleFactoryMethodsProviderSamples.aspx – Custodio 2011-05-11 16:13:38

+0

我们正在使用控制反转。现在在我们的测试中没有使用任何框架。 – GeertvdC 2011-05-12 07:37:13

回答

0

我找到了解决我自己的问题。

我将verifySet替换为正常的断言_mockedviw.object,所以我使用存根来测试,而不是模拟,这是完美的工作。使用我使用的存根功能:

_mockedView.SetupAllProperties(); 

默认情况下不可能比较2个不同的引用对象,所以我只是手动检查属性。

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; 
} 
+0

我知道有2个不同的模型实例。不过,我希望能够检查两者在我的测试中是否相同。 – GeertvdC 2011-05-12 07:39:54

相关问题