在单元测试GetAsync时,如何让HttpResponseMessage返回异常并被catch块捕获?

问题描述 投票:0回答:1

我正在对类似于下面的代码进行单元测试。在一个用例中,我希望 GetAsync 抛出异常并在 catch 块中捕获。

try
{
   var response = await client.GetAsync(url, cancellationToken);
}
catch(Exception e)
{
  _logger.LogError(e)
}

我在嘲笑 HttpClient

var factory = new Mock<IHttpClientFactory>();

var httpClient = new HttpClient(handler)
{
   BaseAddress = new Uri("http://localhost:7100")
}

factory.Setup(_ => _.CreateClient(It.IsAny<string>()))
      .Returns(httpClient)
      .Verifiable();

这里我嘲笑 HttpMessageHandler

var handler = new Mock<HttpMessageHandler>();
handler
    .Protected()
    .Setup<Task<HttpResponseMessage>>(
      "SendAsync",
      ItExpr.IsAny<HttpRequestMessage>(),
      ItExpr.IsAny<CancellationToken>()
    )
    .Returns(GetHttpResponseMessage())
    .Verifiable();

GetHttpResponseMessage() 是我放置逻辑以返回适当的 HttpResponseMassage 的方法。

HttpResponseMessage GetHttpResponseMessage(int code)
{
   if(code == 200)
   {
      return new HttpResponseMessage{ StatusCode = HttpStatusCode.OK };

   }
   else if(code == 500)
   {
      //StatusCode.InternalServerError   ???
      //throw new Exception() ???
   }
}

上面这两个都不起作用。两者都不会导致异常被 catch 块捕获。

感谢您的帮助

moq dotnet-httpclient
1个回答
0
投票

您可以设置异步方法直接抛出异常

using Moq;
using Moq.Protected;
using System;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;

public class YourTestClass
{
    public void TestMethod()
    {
        var factory = new Mock<IHttpClientFactory>();

        var handler = new Mock<HttpMessageHandler>();
        handler
            .Protected()
            .Setup<Task<HttpResponseMessage>>(
                "SendAsync",
                ItExpr.IsAny<HttpRequestMessage>(),
                ItExpr.IsAny<CancellationToken>()
            )
            .Throws(new HttpRequestException("Simulated exception"))
            .Verifiable();

        var httpClient = new HttpClient(handler.Object)
        {
            BaseAddress = new Uri("http://localhost:7100")
        };

        factory.Setup(_ => _.CreateClient(It.IsAny<string>()))
              .Returns(httpClient)
              .Verifiable();

        
        try
        {
           
        }
        catch (HttpRequestException ex)
        {
         
        }
    }
}

© www.soinside.com 2019 - 2024. All rights reserved.