title: Nsubstitute or moq an Async method so it will return a faulted task instead of exception
body: <p>In the below code for each request we are calling rest client in an Async manner. Rest client is basically a http client which is calling some webapis in a batch. If suppose AsyncTaskCount value is 5 then 5 request will be called asynchronously and then in the while block we are getting the result for each call. If any response out of those 5 request has an exception then the response will be faulted and IsFaulted becomes true for that particular request and in the response we can get the inner exception. </p>
  
  <pre><code>private async Task&lt;List&lt;RequestResponse&gt;&gt; ProcessInvestment(List&lt;Request&gt; Requests, List&lt;Result&gt; Results, ILogger log)
      {
  
          var requestResponses = new List&lt;RequestResponse&gt;();
          var asyncTaskCount = Convert.ToInt32(Environment.GetEnvironmentVariable("AsyncTaskCount"));
          log.LogInformation($"Start processing {Requests.Count} in batches of {asyncTaskCount}");
  
          for (int index = 0; index &lt; Requests.Count; index = index + asyncTaskCount)
          {
              var requestBatch = Requests.Skip(index).Take(asyncTaskCount).ToList();
  
              var requests = requestBatch.Select(x =&gt; _restClient.RequestResponse(x)).ToList();
  
              while (requests.Count &gt; 0)
              {
                  // Identify the first task that completes.
                  Task&lt;RequestResponse&gt; requestResponseTask = await Task.WhenAny(requests);
                  var requestResponse = new RequestResponse();
  
                  // ***Remove the selected task from the list so that you don't process it more than once
                  requests.Remove(requestResponseTask);
  
                  if (!requestResponseTask.IsFaulted)
                  {
                      // Await the completed task.
                      requestResponse = await requestResponseTask;
                      requestResponses.Add(requestResponse);
                  }
                  else
                  {
                      if (requestResponseTask.Exception.InnerException != null &amp;&amp; requestResponseTask.Exception.InnerException is Exception)
                      {
                          var result = new Result();
                          result = ResponseTransformComponent.ResponseToResult(((Exception)requestResponseTask.Exception.InnerException).Request, null);
                          result.SetBadRequestErrorDetails(((Exception)RequestResponseTask.Exception.InnerException).BadRequestResponse);
                          results.Add(Result);
                      }
                      else
                      {
                          throw requestResponseTask.Exception;
                      }
                  }
              }
  
              log.LogInformation($"Number of records processed = {requestResponses.Count}");
          }
  
          log.LogInformation($"Total invalid and Bad requests count = {results.Count}");
          return RequestResponses;
      }
  </code></pre>
  
  <p>Below is the code for restclient which is called from the above method.</p>
  
  <pre><code>public async Task&lt;Response&gt; RequestResponse(Request request)
          {
              var response = await GetDataFromService("calculation", "CalculateCapital", request);
  
              return JsonConvert.DeserializeObject&lt;Response&gt;(response);
          }
  
  public async Task&lt;string&gt; GetDataFromService(string controller, string method, object request)
          {
              var client = _httpClientFactory.CreateClient(ServiceEnum.DCS);
  
              string baseAddress = client.BaseAddress.ToString();
  
              var requestUrl = $"api/{controller}/{method}";
              var content = new StringContent(JsonConvert.SerializeObject(request), Encoding.UTF8, "application/json");
              var response = await client.PostAsync(requestUrl, content).ConfigureAwait(false);
              if (!response.IsSuccessStatusCode)
              {
                  var responseResult = response.Content.ReadAsStringAsync().Result;
  
                  if (response.StatusCode == HttpStatusCode.BadRequest)
                  {
                      throw new CalculatorServiceException("Bad Request", JsonConvert.DeserializeObject&lt;BadRequestResponse&gt;(responseResult), (Request)request);
                  }
  
                  throw new Exception($"Status code: {response.StatusCode}. {responseResult}");
              }
  
              return response.Content.ReadAsStringAsync().Result;
          }
  </code></pre>
  
  <p>GetDataFromService method is called from Calculate method. And GetDataFromService method will return a custom exception if the request is a Bad Request.</p>
  
  <p>I am trying to write the unit test case for the above method and try to mock a request so that it will return a faulted task and then IsFaulted should become true. Below is the part of my unit test case.</p>
  
  <pre><code> _restClient
                  .When(a =&gt; a.RequestResponse(Arg.Any&lt;Request&gt;()))
                  .Do(a =&gt; {Task.FromException(new CalculatorServiceException(string.Empty, new BadRequestResponse { Message = string.Empty, ModelState = new Dictionary&lt;string, string[]&gt; { { "CalculationDates.StartDate", new string[] { "0002: Duration too short to execute calculations (CalculationDates.StartDate)" } } } }, Arg.Any&lt;Request&gt;())); });
  </code></pre>
  
  <p>If i mock my restclient method like above then it is throwing the exception instead of giving the response with IsFaulted to true. So how should i mock the restclient method so that it will return a faulted task which has an exception instead of throwing it. Please suggest.</p>
  
  <p>Thanks in advance.</p>