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);
.
.
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With