Wie verspotte ich HttpClient.GetFromJsonAsync?
Posted: 03 Jan 2025, 06:31
Ich habe Code, der GetFromJsonAsync von HttpClient aufruft, aber ich habe Schwierigkeiten, den Methodenaufruf zu verspotten, und frage mich, wie ich das machen kann?
C#-Code:
Ich habe frühere Beiträge gesehen, die vorschlagen, dass ich HttpMessageHandler verspotten sollte, aber wie verspotte ich die Antwort zurück vom GetFromJsonAsync-Methodenaufruf?
Gemäß Als eine der vorgeschlagenen Antworten habe ich Folgendes getan:
Ich erhalte jedoch die folgende Fehlermeldung:
C#-Code:
Code: Select all
public class Client : IClient
{
private readonly IHttpClientFactory _httpClientFactory;
private readonly HttpClient _httpClient;
public Client(IHttpClientFactory httpClientFactory)
{
_httpClientFactory = httpClientFactory;
_httpClient = _httpClientFactory.CreateClient();
}
public async Task GetData()
{
try
{
return await _httpClient.GetFromJsonAsync("endpointUrl"); // How to mock?
}
catch (Exception e)
{
throw;
}
return null;
}
}
Gemäß Als eine der vorgeschlagenen Antworten habe ich Folgendes getan:
Code: Select all
var httpClientMock = new Mock();
httpClientMock.Setup(x => x.GetFromJsonAsync(It.IsAny(), It.IsAny()))
.ReturnsAsync(new ApiResponse());
_httpClientFactoryMock = new Mock();
_httpClientFactoryMock.Setup(x => x.CreateClient(It.IsAny())).Returns(httpClientMock.Object);
Code: Select all
Message "Unsupported expression: x => x.GetFromJsonAsync(It.IsAny(), It.IsAny())\nExtension methods (here: HttpClientJsonExtensions.GetFromJsonAsync) may not be used in setup / verification expressions."