如何编写单元测试用例 IHttpClientFactory

问题描述

我在服务层有一种方法可以连接到服务,我正在使用 IHttpClientFactory。我的方法工作正常。现在我正在尝试为此编写单元测试用例。

public async Task<MyObject> MyMethodAsync(string arg1,string arg2)
{
    var client = _httpClientFactory.CreateClient("XYZ");

    var Authkey = "abc"; 
    var AuthToken = "def";
       
    var headers = new Dictionary<string,string>
        {
            { Authkey,AuthToken }
        };

    client.AddTokenToHeader(headers); //This method set  the DefaultRequestheader from the dictionary object

    var reqData = new
    {
        prop1 = "X",prop2 = "Y"
    };//req object

    var content = new StringContent(JsonConvert.SerializeObject(reqData),Encoding.UTF8,"application/json");

    //This is httpClient Post call for posting data 
    HttpResponseMessage response = await client.PostAsync("postData",content); 
    if (!response.IsSuccessStatusCode || response.Content == null)
    {
        return null;
    }

    MyObject myObject = JsonConvert.DeserializeObject<MyObject>(response.Content.ReadAsStringAsync().Result);//read the result to an object
    return myObject;
}

对于上述方法,我正在编写测试用例。在这里,我试图将 Post 方法设置为输出状态代码 OK 并期待 MyMethodAsync 方法为真,因为 PostAsync 为真。在这里我得到一个例外

System.InvalidOperationException:提供了无效的请求 URI。请求 URI 必须是绝对 URI 或必须设置 BaseAddress。

[Test]
public async Task MyMethodAsync_Gets_True()
{
    var response = new HttpResponseMessage(HttpStatusCode.OK)
    {
        Content = new StringContent("It worked!")
    };

    //Mock the httpclientfactory
    var _httpMessageHandler = new Mock<HttpMessageHandler>();
    var mockFactory = new Mock<IHttpClientFactory>(); 

    //Specify here the http method as post
    _httpMessageHandler.Protected()
      .Setup<Task<HttpResponseMessage>>("SendAsync",ItExpr.Is<HttpRequestMessage>(req => req.Method == HttpMethod.Post),ItExpr.IsAny<CancellationToken>())
       .ReturnsAsync(new HttpResponseMessage
       {
           StatusCode = HttpStatusCode.OK
       });


    var httpClient = new HttpClient(_httpMessageHandler.Object);
    mockFactory.Setup(_ => _.CreateClient(It.IsAny<string>())).Returns(httpClient);

    var arg1 = "X";
    var arg2 = "D101";

    var service = new MyService(_mockAppSettings.Object,mockFactory.Object);
    var result = await service.MyMethodAsync(arg1,arg2);
    // Assert
    Assert.IsNotNull(result);
}

有人可以告诉我在这里犯了什么错误吗?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)