Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Async

Testing Async Requests, Mocking Async Methods with New Ivonna

0.00/5 (No votes)
8 Mar 2013CPOL2 min read 7.9K  
Testing Async Requests, Mocking Async Methods with New Ivonna

For those of you who can't wait to start testing async requests, here's the good news (and no, there is no bad news in this post): starting with the 3.1 version of Ivonna, you can test them with the same syntax as before, i.e., using either session.Get(url) or session.GetPage(url).

However, this is not the end of the story. Most of the time, you use the async pattern for a reason. You have a lengthy operation in your Web code. And that's the other good news: now you can mock async methods called from your controllers/codebehind/whatever, returning custom values. This functionality is a part of the Ivonna.Framework.MVC assembly, but you can use it with any Web framework -- it's not really related to MVC, but I didn't put it into Ivonna itself since I didn't want to introduce the .NET 4.0 dependency (this might change in the future).

Suppose you have the following code that you want to test (taken from MSDN):

C#
public async Task<ActionResult> About() {
	var client = new HttpClient();
	string urlContents = await client.GetStringAsync("http://msdn.microsoft.com");
	return Content(urlContents);
}

You can test the whole method, but the test would have wait for the HttpClient to return the result, which can take a long time, and be unpredictable. In addition, you might want to test your controller's logic, not the code that runs the MSDN site. So, you want a predictable return value, and you want it fast. Here is how the new functionality helps you:

C#
var session = new TestSession();
var fakeResponseString = "We Are Microsoft";
session.Stub<HttpClient>("GetStringAsync").ReturnFromAsync(fakeResponseString);

There's also a strongly typed lambda-based overload, but personally I find it less convenient and more noisy. Note that a stub like this works on all requests for all instances of HttpClient, so if you want a more fine grained control, you'll have to implement your own CThru aspect.

One more gotcha here. Some useful async methods are implemented as extensions, so you cannot use the syntax above. Use more verbose session.AddAspect(new Stub(..)) instead.

I really hope you'll find these new features useful. Enjoy!

P.S.: I strongly suggest that you use this opportunity to save 16% on Ivonna and Isolator (ends March 31st).

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)