C# 测试基于任务的WCF调用
我将在应用程序中进行的WCF调用转换为异步运行,以确保GUI在获取数据时响应良好。我主要使用这些方法来填充ViewModel的属性 例如,我的新旧代码如下:C# 测试基于任务的WCF调用,c#,wpf,unit-testing,task-parallel-library,rhino-mocks,C#,Wpf,Unit Testing,Task Parallel Library,Rhino Mocks,我将在应用程序中进行的WCF调用转换为异步运行,以确保GUI在获取数据时响应良好。我主要使用这些方法来填充ViewModel的属性 例如,我的新旧代码如下: private async Task LoadDataItems() { //DataItems = Service.SelectDataItems(); DataItems = await Service.SelectDataItemsAsync(); } 另外,这里有一些使用Rhinomock的测试代码: //Doe
private async Task LoadDataItems()
{
//DataItems = Service.SelectDataItems();
DataItems = await Service.SelectDataItemsAsync();
}
另外,这里有一些使用Rhinomock的测试代码:
//Doesn't set DataItems when LoadDataItems() is called
myWcfServiceClient.Stub(async client => await client.SelectDataItemsAsync()).Return(new Task<List<DataItemDto>>(() => new List<DataItemDto> { testDataItem }));
//NullReferenceException on SelectDataItemsAsync()
myWcfServiceClient.Stub(client => client.SelectDataItemsAsync().Result).Return(new List<DataItemDto> { testDataItem });
//调用LoadDataItems()时不设置DataItems
myWcfServiceClient.Stub(异步客户端=>等待客户端.SelectDataItemsAsync()).Return(新任务(()=>新列表{testDataItem}));
//SelectDataItemsAsync()上的NullReferenceException
myWcfServiceClient.Stub(client=>client.SelectDataItemsAsync().Result).Return(新列表{testDataItem});
基本上,在我的单元测试中,要么没有设置
DataItems
,要么我得到一个NullReferenceException试图伪造结果。这可能是Rhinomock上的一个问题,而不是任何问题…在Rhinomock中,您可以使用Task.FromResult(…)
因此,我的测试代码将设置结果如下:
myWcfServiceClient.Stub(client => client.SelectDataItemsAsync()).Return(Task.FromResult(new List<DataItemDto> { testDataItem }));
myWcfServiceClient.Stub(client=>client.SelectDataItemsAsync()).Return(Task.FromResult(新列表{testDataItem}));
简单和伟大的作品