651.288.7000 info@intertech.com

With the addition of the async/await keywords in .NET Framework 4.5, many more methods will now return Task<TResult>.  For example, a web service method can now be created to return Task<TResult> so it is ready for the async/await keywords.  This brings up the question on how you can unit test these methods.  Or maybe you are caching something in memory and want to return it instead of having to call a web service with the await keyword.

Luckily in .NET Framework 4.5 there is an elegant way to accomplish the preceding scenarios:  the Task.FromResult method.  Basically, this method creates a Task that is successfully completed with a result you supply as a parameter.  This eliminates the need for you to create a Task and start it when the result is known.


This example will show how to test a mythical web service that returns a greeting as a Task<string>.  Here is the web service facade’s interface and implementation:

Now suppose you want to unit test the GetGreeting method.  Assuming it actually called a web service, you wouldn’t want your unit test to call the real GetGreeting so the following code shows how to mock it using NSubstitute:

The key part to see is the mock of GetGreeting.  It Returns Task.FromResult(greeting).  This makes it quite simple to specify a Task return value.  The Assert assures us that the greeting we created in the unit test is the one that was returned.


You can see in my simple unit test example that it can be very easy to return a Task<TResult> using the Task.FromResult method.  For more information on .NET unit testing, see the Intertech class on the subject here:  http://www.intertech.com/Training/Microsoft/Visual-Studio/Unit-Testing/Unit-Testing-in-Visual-Studio-2012

Here’s an example of using Task.FromResult in a caching scenario:  http://msdn.microsoft.com/en-us/library/hh228607.aspx

Pin It on Pinterest

Share This

Like What You've Read?

Subscribe to the Blog.

Every Friday we send that week's content from our Developers via email. Try it out!

Some ad blockers can block the form below.

You have Successfully Subscribed!