title: How can I throw Exception for async function using Moq
body: <p>I am writing test cases using xUnit and Moq.</p>
  
  <p>I am using below code in Test class for testing <code>catch()</code> of another class method</p>
  
  <pre><code>private readonly  IADLS_Operations _iADLS_Operations;
  
  [Fact]
  public void CreateCSVFile_Failure()
  {
      var dtData = new DataTable();
      string fileName = "";
     var   mockClient = new Mock&lt;IHttpHandler&gt;();
  
      this._iADLS_Operations = new ADLS_Operations(mockClient.Object);
  
      mockClient.Setup(repo =&gt; repo.PostAsync(It.IsAny&lt;string&gt;(), It.IsAny&lt;HttpContent&gt;(), It.IsAny&lt;string&gt;()))
          .Returns(() =&gt; Task.FromResult(new HttpResponseMessage(HttpStatusCode.BadRequest)));
  
      mockClient.Setup(repo =&gt; repo.SendAsync(It.IsAny&lt;HttpRequestMessage&gt;(), It.IsAny&lt;string&gt;()))
          .Returns(() =&gt; Task.FromResult(new HttpResponseMessage(HttpStatusCode.BadRequest)));  // here I want to return Exception instead of BadRequest. How to do that.
  
      Exception ex = Assert.Throws&lt;Exception&gt;(() =&gt; this._iADLS_Operations.CreateCSVFile(dtData, fileName).Result);
      Assert.Contains("Exception occurred while executing method:", ex.Message);
  }
  </code></pre>
  
  <p>In below code, I want to return Exception instead of <code>BadRequest</code>. </p>
  
  <pre><code>mockClient.Setup(repo =&gt; repo.SendAsync(It.IsAny&lt;HttpRequestMessage&gt;(), It.IsAny&lt;string&gt;()))
      .Returns(() =&gt; Task.FromResult(new HttpResponseMessage(HttpStatusCode.BadRequest)));
  </code></pre>
  
  <p>How to achieve that.</p>