michielpost.nl

Windows 8 async programming and mocking async methods in MVVM

11-07-2012

Consider you created a service interface with a method which has a return type of Task:

public interface IMyService
{
  Task<string> GetStringAsync();
}

When you inplement this interface, you're probably doing some async calls in your method:

public class MyService : IMyService
{
  public async Task<string> GetStringAsync()
  {
     string result = await DoAsyncWebRequestEtc();
 
     return string;
  }
}

The method returns a Task, but because the method is marked async, you can just return a string.
See MSDN (Async Return Types) for more info http://msdn.microsoft.com/en-us/library/hh524395(v=vs.110).aspx

But when you're creating a mock for this service, you're not going to do any async calls. So you don't need the async, but then you have to return an actual Task. That's not what we want.

If we keep the async and just return a string, we will get a compiler warning about a lacking await operator:

public class MyServiceMock : IMyService
{
  public async Task<string> GetStringAsync()
  {
     return "mock string";
  }
}

Warning from Visual Studio:
This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.

We can fix this by dropping the async and return an actual task by using the helper Task.FromResult.

public class MyServiceMock : IMyService
{
  public Task<string> GetStringAsync()
  {
     return Task.FromResult("mock string");
  }
}

The compiler is happy and we keep our blendability with MVVM Light. (Value shows up in the UI when using MVVM Light).

 

Comments


Mattias 17-02-2013
Super! But what about the other case when there is no return value: Task DoWorkAsync(); You cannot call FromResult() with no arguments... :/


New Comment

Name
E-mail (not published)
Comment
Enter the code shown: