mardi 27 janvier 2015

C# Testing Asynchronous/Callbacks Visual Studio

I need to write some tests for a whole bunch of C# code similar to the below example. This is one of my first tasks in C# and I've been unlucky enough to get dumped straight into async code :(. Its a web application that makes a bunch of database requests:



namespace Foo.ViewModel
{
public class FooViewModel
{
private ManagementService _managementService;
public int Status { get; set; }
public Foo()
{
Status = 5;
_managementService = new ManagementService();
_managementService.GetCustomerInfoCompleted += new EventHandler<GetCustomerInfoEventArgs>(CustomerInfoCallback);

}

public void GetCustomerInfo(int count)
{
int b;
if (someCondition() || otherCondition())
{
b = 2;
}
else
{
b = SomeOtherAsynchronousMethod();
}
_managementService.GetCustomerInfoAsync(b, count);
//when completed will call CustomerInfoCallback
}

void CustomerInfoCallback(object sender, GetCustomerInfoEventArgs args)
{
Status = args.Result.Result.Total;
UpdateView();
}

}

}


I'd like to be able to run a simple test like this:



[TestMethod]
public void TestExecute5()
{
Foo f = new Foo();
f.GetCustomerInfo(5);
Assert.AreEqual(10, f.Status);
}


but obviously its not that simple with the anynchronous methods.


There are perhaps 40 asynchronous methods in the ManagementService, called by ~15 different ViewModels - this ViewModel calls about 8 of those asynchronous methods. The async calls are implemented through the Event-Based Asynchronous Pattern so we don't have any of the nice 'async' or 'await' functions.


What can I do to get tests working in some kind of way that I can call the GetCustomerInfo method and check the status after the callback has completed?


Aucun commentaire:

Enregistrer un commentaire