views:

374

answers:

3

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

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.

Bermo
+4  A: 

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);
    }
}
Mark Seemann
Awesome, this worked great. Thank you!
Charlie
A: 

Guys,

Am getting System.TypeInitializationException Runtime exception while creating Mock object for IAsyncResult.

IAsyncResult asyncResult = new Mock<IAsyncResult>().Object;

Please help me to solve this..

Senthil