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