简体   繁体   English

测试基于任务的WCF调用

[英]Testing Task-based WCF call

I am converting the WCF calls I am making in an application to run asynchronously to ensure the GUI is responsive while it gets data. 我正在将在应用程序中进行的WCF调用转换为异步运行,以确保GUI在获取数据时能够响应。 Mostly I am using these methods to populate the properties of a ViewModel. 通常,我使用这些方法来填充ViewModel的属性。

For instance, here's my old and new code: 例如,这是我的新旧代码:

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

    DataItems = await Service.SelectDataItemsAsync();
}

Also, here's some test code using RhinoMocks: 另外,这是一些使用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 });

Basically, in my unit test, either DataItems isn't set or I get a NullReferenceException trying to fake out the result. 基本上,在我的单元测试中,未设置DataItems或得到了NullReferenceException试图伪造结果。 This is probably as much a question on RhinoMocks than anything... 在RhinoMocks上,这可能比什么都重要。

In RhinoMocks, you define the Result on the Task-based operation with Task.FromResult(...) 在RhinoMocks中,您可以使用Task.FromResult(...)在基于任务的操作上定义Result Task.FromResult(...)

So, my test code would set up the result as follows: 因此,我的测试代码将如下设置结果:

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

Simple and works great! 简单,效果很好!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM