public abstract class IntegrationTest : IDisposable
{
protected readonly HttpClient TestClient;
private readonly CosmosDbContainer _cosmosDbContainer = new CosmosDbBuilder()
.WithPortBinding(0, 8081)
.Build();
protected IntegrationTest()
{
TestClient = InitializeClient().GetAwaiter().GetResult();
}
public async Task InitializeAsync()
{
await _cosmosDbContainer.StartAsync();
Console.WriteLine($"Mapped public port for Cosmos DB: {_cosmosDbContainer.GetMappedPublicPort(8081)}");
}
public async Task DisposeAsync()
{
await _cosmosDbContainer.DisposeAsync().AsTask();
}
private async Task<HttpClient> InitializeClient()
{
await InitializeAsync();
var appFactory = new WebApplicationFactory<Program>()
.WithWebHostBuilder(builder =>
{
builder.ConfigureServices(services =>
{
var connectionString = _cosmosDbContainer.GetConnectionString();
Console.WriteLine($"Connection string generated: {connectionString}");
var cosmosOptions = new CosmosClientOptions
{
Serializer = new CosmosJsonSerializer(),
ConnectionMode = ConnectionMode.Gateway,
HttpClientFactory = () => _cosmosDbContainer.HttpClient
};
services.RemoveAll(typeof(CosmosClient));
services.AddSingleton(new CosmosClient(connectionString, cosmosOptions));
});
builder.UseEnvironment("Development");
});
return appFactory.CreateClient();
}
public void Dispose()
{
TestClient.Dispose();
DisposeAsync().GetAwaiter().GetResult();
}