title: Using Moq to mock an asynchronous method for a unit test
body: <p>I am testing a method for a service that makes a Web <code>API</code> call. Using a normal <code>HttpClient</code> works fine for unit tests if I also run the web service (located in another project in the solution) locally. </p>
  
  <p>However when I check in my changes the build server won't have access to the web service so the tests will fail.</p>
  
  <p>I've devised a way around this for my unit tests by creating an <code>IHttpClient</code> interface and implementing a version that I use in my application. For unit tests, I make a mocked version complete with a mocked asynchronous post method. Here's where I have run into problems. I want to return an OK <code>HttpStatusResult</code> for this particular test. For another similar test I will be returning a bad result. </p>
  
  <p>The test will run but will never complete. It hangs at the await. I am new to asynchronous programming, delegates, and Moq itself and I've been searching SO and google for a while learning new things but I still can't seem to get past this problem.</p>
  
  <p>Here is the method I am trying to test:</p>
  
  <pre><code>public async Task&lt;bool&gt; QueueNotificationAsync(IHttpClient client, Email email)
  {
      // do stuff
      try
      {
          // The test hangs here, never returning
          HttpResponseMessage response = await client.PostAsync(uri, content);
  
          // more logic here
      }
      // more stuff
  }
  </code></pre>
  
  <p>Here's my unit test method:</p>
  
  <pre><code>[TestMethod]
  public async Task QueueNotificationAsync_Completes_With_ValidEmail()
  {
      Email email = new Email()
      {
          FromAddress = "bob@example.com",
          ToAddress = "bill@example.com",
          CCAddress = "brian@example.com",
          BCCAddress = "ben@example.com",
          Subject = "Hello",
          Body = "Hello World."
      };
      var mockClient = new Mock&lt;IHttpClient&gt;();
      mockClient.Setup(c =&gt; c.PostAsync(
          It.IsAny&lt;Uri&gt;(),
          It.IsAny&lt;HttpContent&gt;()
          )).Returns(() =&gt; new Task&lt;HttpResponseMessage&gt;(() =&gt; new HttpResponseMessage(System.Net.HttpStatusCode.OK)));
  
      bool result = await _notificationRequestService.QueueNotificationAsync(mockClient.Object, email);
  
      Assert.IsTrue(result, "Queue failed.");
  }
  </code></pre>
  
  <p>What am I doing wrong?</p>
  
  <p>Thank you for your help.</p>