0

我在服务层中有一个方法可以连接到服务,我正在使用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方法为 true,因为它PostAsync是 true。在这里我遇到了一个例外

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);
}

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

4

1 回答 1

1

正如例外所说,你必须

  • 要么PostAsync用绝对网址调用
  • 或设置BaseAddressHttpClient 的

如果您选择第二个,您需要做的就是:

var httpClient = new HttpClient(_httpMessageHandler.Object);

httpClient.BaseAddress = new Uri("http://nonexisting.domain"); //New code

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

通过此修改,异常将消失。
但是您的测试将失败,因为response.Content将是null,这就是为什么MyMethodAsync将返回null.

要解决此问题,让我们将设置更改为:

public static async Task MyMethodAsync_Gets_True()
{
    //Arrange
    MyObject resultObject = new MyObject();
    var response = new HttpResponseMessage(HttpStatusCode.OK)
    {
        Content = new StringContent(JsonConvert.SerializeObject(resultObject))
    };

    var _httpMessageHandler = new Mock<HttpMessageHandler>();
    _httpMessageHandler.Protected()
        .Setup<Task<HttpResponseMessage>>("SendAsync",
          ItExpr.Is<HttpRequestMessage>(req => req.Method == HttpMethod.Post),
          ItExpr.IsAny<CancellationToken>())
        .ReturnsAsync(response);
    ...

    //Act
    var result = await service.MyMethodAsync(arg1, arg2);

    //Assert
    Assert.NotNull(result);
}
于 2021-05-07T07:22:56.697 回答