Přeskočit na hlavní obsah

Testcontainers guides

Testcontainers and WebApplicationFactory Guide

The following explains how to integrate a testcontainer instance with ASP.NET Core integration tests built on WebApplicationFactory<TEntryPoint>.

WebApplicationFactory with a built-in Testcontainer

public class SpecificApplicationFactory : WebApplicationFactory<Program>, IAsyncLifetime
{
private TestContainer _testContainer;

public SpecificApplicationFactory()
{
_testContainer = new TestContainer("testcontainer")
.Build();
}

public Task InitializeAsync()
{
return _testContainer.StartAsync();
}

public new async Task DisposeAsync()
{
await _testContainer.StopAsync();
await _testContainer.DisposeAsync();
}

protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder.ConfigureAppConfiguration(config =>
{
KeyValuePair<string, string>[] collection =
[
new KeyValuePair<string, string>(
key: $"ConnectionStrings:TestContainer",
value: _testContainer.GetConnectionString())
];

return configurationBuilder.AddInMemoryCollection(collection!);
});
}
}

public class ExampleTests : IClassFixture<SpecificApplicationFactory>
{
private readonly HttpClient _client;

public ExampleTests(SpecificApplicationFactory factory)
{
_client = factory.CreateClient();
}

[Fact]
public async Task Get_ReturnsSuccess()
{
var response = await _client.GetAsync("/api/values");
response.EnsureSuccessStatusCode();
}
}