测试基于任务的WCF调用

时间:2014-01-24 15:08:40

标签: c# wpf unit-testing task-parallel-library rhino-mocks

我正在将我在应用程序中进行的WCF调用转换为异步运行,以确保GUI在获取数据时具有响应能力。大多数情况下,我使用这些方法来填充ViewModel的属性。

例如,这是我的新旧代码:

private async Task LoadDataItems()
{
    //DataItems = Service.SelectDataItems();

    DataItems = await Service.SelectDataItemsAsync();
}

此外,这里有一些使用RhinoMocks的测试代码:

//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 });

基本上,在我的单元测试中,未设置DataItems或者我得到NullReferenceException试图伪造结果。这可能是关于RhinoMocks的问题,而不是任何事情......

1 个答案:

答案 0 :(得分:1)

在RhinoMocks中,您使用Result

在基于任务的操作上定义Task.FromResult(...)

因此,我的测试代码会将结果设置如下:

myWcfServiceClient.Stub(client => client.SelectDataItemsAsync()).Return(Task.FromResult(new List<DataItemDto> { testDataItem }));

简单而且效果很好!