Wie verspotte ich HttpClient.GetFromJsonAsync?C#

Ein Treffpunkt für C#-Programmierer
Guest
 Wie verspotte ich HttpClient.GetFromJsonAsync?

Post by Guest »

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:

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

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);
Ich erhalte jedoch die folgende Fehlermeldung:

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."

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post