public static HttpClient _client1;
public static HttpClient _client2;
[OneTimeSetUp]
public void OneTimeSetUp()
{
_client1 = new HttpClient {BaseAddress = new Uri("https://address1.com")};
_client1.DefaultRequestHeaders.Add("API-KEY", "token_here");
_client2 = new HttpClient {BaseAddress = new Uri("https://address2.com")};
_client1.DefaultRequestHeaders.Add("API-KEY", "token_here");
}
//[OneTimeTearDown]
//public void OneTimeTearDown()
//{
//_client1?.Dispose();
//_client2?.Dispose();
//}
public static HttpClient _client1;
public static HttpClient _client2;
[OneTimeSetUp]
public void OneTimeSetUp()
{
var services = new ServiceCollection();
services.AddHttpClient("Client1", client =>
{
client.BaseAddress = new Uri("https://address1.com/");
client.DefaultRequestHeaders.Add("KEY", "token_here");
});
services.AddHttpClient("Client2", client =>
{
client.BaseAddress = new Uri("https://address2.com/");
client.DefaultRequestHeaders.Add("KEY", "token_here");
});
var factory = services.BuildServiceProvider().GetService<IHttpClientFactory>();
_client1 = factory.CreateClient("Client1");
_client2 = factory.CreateClient("Client2");
}
//[OneTimeTearDown]
//public void OneTimeTearDown()
//{
//_client1?.Dispose();
//_client2?.Dispose();
//}
[TestFixture][TestFixture, Parallelizable(ParallelScope.All)]
public class TestCase : Setup
{
[Test]
public async Task Get()
{
var response = await _client1.GetAsync("v1/Endpoint");
response.EnsureSuccessStatusCode();
var result = await response.Content.ReadAsStringAsync();
Assert.NotNull(response);
Console.WriteLine(JToken.Parse(result));
}
}
As I said, it works as expected on both ways, but since I'm new at this and didn't found much about this kind of integration test separated from the main API reference project, I'm not so sure about how I built it, so any other and more experienced views about it will be very much appreciated.
EDIT: I had the need to run all the tests in parallel, so I was generating an ObjectDisposedException with the Parallelizable attribute. Removing the OneTimeTearDown with the client disposing calls solved the problem, but I have doubts if that's the correct way to use HttpClient as well, as it still gives the expected results.