我如何模拟这个异步方法?
我有一个大致如下所示的类:
public class ViewModel
{
public ViewModel(IWebService service)
{
this.WebService = service;
}
private IWebService WebService{get;set;}
private IEnumerable<SomeData> MyData{get;set;}
private void GetReferenceData()
{
this.WebService.BeginGetStaticReferenceData(GetReferenceDataOnComplete, null);
}
private void GetReferenceDataOnComplete(IAsyncResult result)
{
this.MyData = this.WebService.EndGetStaticReferenceData(result);
}
.
.
.
}
我想模拟我的 IWebService 接口,以便在调用 BeginGetStaticReferenceData 时它能够调用回调方法。我正在使用 Moq,但我不知道如何做到这一点。我的单元测试设置代码如下所示:
//Arrange
var service = new Mock<IWebService>();
service.Setup(x => x.BeginGetStaticReferenceData(/*.......don't know.....*/));
service.Setup(x => x.EndGetStaticReferenceData(It.IsAny<IAsyncResult>())).Returns(new List<SomeData>{new SomeData{Name="blah"}});
var viewModel = new ViewModel(service.Object);
.
.
I have a class that roughly looks like this:
public class ViewModel
{
public ViewModel(IWebService service)
{
this.WebService = service;
}
private IWebService WebService{get;set;}
private IEnumerable<SomeData> MyData{get;set;}
private void GetReferenceData()
{
this.WebService.BeginGetStaticReferenceData(GetReferenceDataOnComplete, null);
}
private void GetReferenceDataOnComplete(IAsyncResult result)
{
this.MyData = this.WebService.EndGetStaticReferenceData(result);
}
.
.
.
}
I want to mock my IWebService interface so that when BeginGetStaticReferenceData is called it is able to call the callback method. I'm using Moq and I can't work out how to do this. My unit test set up code looks something like:
//Arrange
var service = new Mock<IWebService>();
service.Setup(x => x.BeginGetStaticReferenceData(/*.......don't know.....*/));
service.Setup(x => x.EndGetStaticReferenceData(It.IsAny<IAsyncResult>())).Returns(new List<SomeData>{new SomeData{Name="blah"}});
var viewModel = new ViewModel(service.Object);
.
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
方法如下:
此测试假设对 ViewModel 进行了稍微修改,其中我添加了一些公共成员来进行测试:
Here's how:
This test assumes a slightly modified ViewModel where I added a few public members to have something against which to test:
这篇文章包含了关于如何使用Rhino测试异步方法的很好的解释Mocks - 我相信它可以很容易地适应使用 Moq 来代替。
This article contains a very good explanation on how to test async methods using Rhino Mocks - I'm sure it can be easily adapted to use Moq instead.