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.

Example

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:

public interface IWSFacade
{
    Task<string> GetGreeting();
}

public class WSFacade : IWSFacade
{
    public async Task<string> GetGreeting()
    {
        return await Task.FromResult("Hello");
    }
}

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:

[TestMethod]
public void WebService_Test()
{
    // Arrange
    const string greeting = "My greeting test.";
    var webSvcFacade = Substitute.For<IWSFacade>();
    webSvcFacade.GetGreeting().Returns(Task.FromResult(greeting));

    // Act
    var actual = webSvcFacade.GetGreeting();

    // Assert
    Assert.AreEqual(greeting, actual.Result, "Unexpected greeting.");
}

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.

Conclusion

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.