Open vgoranski opened 7 months ago
The AddHttpClient
extension will register a HttpClient
service,
so the HttpClient
registered would be HttpClient
in this case, you can inject IHost host
and use host.GetTestClient()
to get a test HttpClient
Edit >> add a sample
public class ServiceTest(IHost host)
{
private readonly HttpClient _testClient = host.GetTestClient();
[Fact]
public async Task ApiTest()
{
using var response = await _testClient.GetAsync("/");
response.EnsureSuccessStatusCode();
}
}
The solution with host.GetTestClient()
works fine, but it creates a new HttpClient
for every test class. I guess it would be better if the HttpClient
for the test server is used as a singleton?
I guess it would be better if the HttpClient for the test server is used as a singleton?
I think so, while since the test HttpClient would not create a socket connection or send a real request , it would be cheap to create a new one, so it may be acceptable for tests. Since HttpClient is thread-safe, so I think we could keep it as a singleton
Trying to propose an ITestClientWrapper
, does this make sense?
https://github.com/pengweiqhca/Xunit.DependencyInjection/pull/115
Describe the bug When using
MinimalApiHostBuilderFactory.GetHostBuilder<Program>()
andProgram.cs
hasbuilder.Services.AddHttpClient()
it seems that the test server is not created and injectedHttpClient
in the test class hasBaseAddress = null
To Reproduce
Program.cs
MinimalApiTest.cs
Expected behavior
builder.Services.AddHttpClient
inProgram.cs
should not prevent the creation of the test server.