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 are 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/whetever, 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):

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:
var session = new TestSession();
var fakeResponseString = "We Are Microsoft";

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).

blog comments powered by Disqus

Latest blog posts

Powered by FeedBurner