Intégration test with HttpClient
Hi guys,
I'm trying to create some specflow tests and using a WebApplicationFactory and want to moq HttpClient calls with Moq.Contrib.HttpClient.
So i've 2 differents HttpClients
var httpMessageHandler1 = new Mock<HttpMessageHandler>();
httpMessageHandler1.SetupRequest(HttpMethod.Post, $"http://localhost/api/Method1");
var httpMessageHandler2 = new Mock<HttpMessageHandler>();
httpMessageHandler2
.SetupRequest(HttpMethod.Post, $"http://localhost/api/Method2")
.ReturnsResponse(JsonSerializer.Serialize(response), "application/json");
I inject them like this in the stepDefinition class :
var application = new WebFactory<Program>()
.WithWebHostBuilder(builder =>
{
builder.ConfigureServices(services =>
{
var serviceProvider = services.BuildServiceProvider();
services.AddMediatR(typeof(DeviceRequestModel));
services.AddHttpClient("Client1").ConfigurePrimaryHttpMessageHandler(() => httpMessageHandler1.Object);
services.AddHttpClient("Client2").ConfigurePrimaryHttpMessageHandler(() => httpMessageHandler2.Object);
});
});
Here is my WebFactory :
internal class WebFactory<TStartup> : WebApplicationFactory<TStartup> where TStartup : class
{
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
base.ConfigureWebHost(builder);
builder.UseEnvironment(Environments.Development);
builder.UseTestServer()
.ConfigureTestServices(
services =>
{
services.AddScoped<TStartup>();
// Remove existing IHttpClientFactory and HttpClient
var httpClientFactoryDescriptor = services.SingleOrDefault(d => d.ServiceType == typeof(IHttpClientFactory));
services.Remove(httpClientFactoryDescriptor);
var httpClientDescriptor = services.SingleOrDefault(d => d.ServiceType == typeof(HttpClient));
services.Remove(httpClientDescriptor);
});
}
}
In my Command, i get the IHttpClientFactory
public Handler(IHttpClientFactory factory)
{
this.client = factory.CreateClient("Client1");
}
So when i do the HttpResponseMessage response = await this.client.PostAsync i've got this exception Exception levée : 'System.InvalidOperationException' dans System.Net.Http.dll and my client is not intiated well (doesn't match with the moq)
Any ideas?
Thanks
0
Please sign in to leave a comment.
Comments
0 comments