Skip to content

Instantly share code, notes, and snippets.

@dj-nitehawk
Last active May 2, 2024 06:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dj-nitehawk/04a78cea10f2239eb81c958c52ec84e0 to your computer and use it in GitHub Desktop.
Save dj-nitehawk/04a78cea10f2239eb81c958c52ec84e0 to your computer and use it in GitHub Desktop.
Integration testing with TestContainers & AppFixture
using Testcontainers.MongoDb;
public class Sut : AppFixture<Program>
{
const string Database = "TestingDB";
const string RootUsername = "root";
const string RootPassword = "password";
MongoDbContainer _container = null!;
protected override async Task PreSetupAsync()
{
//this function is only ever called once before the WAF/SUT instance is created & cached.
//every derived AppFixture type will cache just one instance of a WAF/SUT.
//more info: https://fast-endpoints.com/docs/integration-unit-testing#app-fixture
_container = new MongoDbBuilder()
.WithImage("mongo")
.WithUsername(RootUsername)
.WithPassword(RootPassword)
.WithCommand("mongod")
.Build();
await _container.StartAsync();
}
protected override void ConfigureApp(IWebHostBuilder b)
{
b.ConfigureAppConfiguration(
c =>
{
c.AddInMemoryCollection(
new Dictionary<string, string?>
{
{ "Mongo:Host", _container.Hostname },
{ "Mongo:Port", _container.GetMappedPublicPort(27017).ToString() },
{ "Mongo:DbName", Database },
{ "Mongo:UserName", RootUsername },
{ "Mongo:Password", RootPassword }
});
});
}
protected override async Task TearDownAsync()
{
//await _container.DisposeAsync();
//NOTE: there's no need to dispose the container here as it will be automatically disposed by testcontainers pkg when the test run finishes.
// this is especially true if this AppFixture is used by many test-classes with WAF caching enabled.
// so, in general - containers don't need to be explicitly disposed, unless you disable WAF caching.
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment