我在服务层中有一个方法可以连接到服务,我正在使用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);
}
有人可以显示我在这里犯了什么错误吗?