我该如何模拟这个异步方法?

时间:2010-03-25 11:15:45

标签: c# unit-testing asynchronous mocking moq

我的课程大致如下:

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);
.
.

2 个答案:

答案 0 :(得分:19)

以下是:

[TestMethod]
public void Test10()
{
    var expectedData = new[]{new SomeData(), new SomeData()};

    AsyncCallback callback = null;
    IAsyncResult ar = new Mock<IAsyncResult>().Object;

    var webServiceStub = new Mock<IWebService>();
    webServiceStub
        .Setup(ws => ws.BeginGetStaticReferenceData(It.IsAny<AsyncCallback>(), null))
        .Callback((AsyncCallback cb, object state) => callback = cb)
        .Returns(ar);
    webServiceStub
        .Setup(ws => ws.EndGetStaticReferenceData(It.IsAny<IAsyncResult>()))
        .Returns(expectedData);

    var sut = new ViewModel(webServiceStub.Object);
    sut.DoIt();

    callback(ar);

    Assert.AreEqual(expectedData, sut.MyData);
}

此测试假设稍微修改了ViewModel,我在其中添加了一些公共成员以获取要测试的内容:

public class ViewModel
{
    public ViewModel(IWebService service)
    {
        this.WebService = service;
    }

    public IEnumerable<SomeData> MyData { get; set; }

    public void DoIt()
    {
        this.GetReferenceData();
    }

    private IWebService WebService { get; set; }

    private void GetReferenceData()
    {
        this.WebService.BeginGetStaticReferenceData(GetReferenceDataOnComplete, null);
    }

    private void GetReferenceDataOnComplete(IAsyncResult result)
    {
        this.MyData = this.WebService.EndGetStaticReferenceData(result);
    }
}

答案 1 :(得分:0)

这个article包含了如何使用Rhino Mocks测试异步方法的非常好的解释 - 我确信它可以很容易地适应使用Moq。