New Ivonna V3.1 – Testing async requests, mocking async methods

BY ARTEM SMIRNOV

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

 

   1: public async Task<ActionResult> About() {

   2:     var client = new HttpClient();

   3:     string urlContents = await client.GetStringAsync("http://msdn.microsoft.com");

   4:     return Content(urlContents);

   5: }

 

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:

 

   1: var session = new TestSession();

   2: var fakeResponseString = "We Are Microsoft";

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

TOP