Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I mock this asynchronous method?

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);
.
.
like image 879
Charlie Avatar asked Mar 25 '10 11:03

Charlie


1 Answers

Here's how:

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

This test assumes a slightly modified ViewModel where I added a few public members to have something against which to test:

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);
    }
}
like image 62
Mark Seemann Avatar answered Oct 23 '22 01:10

Mark Seemann