Skip to content

MongoDB

MongoDB is a cross-platform document-oriented database. MongoDB's document model is simple for developers to use within their applications, while still providing all the complex capabilities of traditional relational databases.

Add the following dependency to your project file:

NuGet
1
dotnet add package Testcontainers.MongoDb

You can start a MongoDB container instance from any .NET application. Here, we create different container instances and pass them to the base test class. This allows us to test different configurations.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
[UsedImplicitly]
public sealed class MongoDbDefaultConfiguration : MongoDbContainerTest
{
    public MongoDbDefaultConfiguration()
        : base(new MongoDbBuilder().Build())
    {
    }
}

[UsedImplicitly]
public sealed class MongoDbNoAuthConfiguration : MongoDbContainerTest
{
    public MongoDbNoAuthConfiguration()
        : base(new MongoDbBuilder().WithUsername(string.Empty).WithPassword(string.Empty).Build())
    {
    }
}

This example uses xUnit.net's IAsyncLifetime interface to manage the lifecycle of the container. The container is started in the InitializeAsync method before the test method runs, ensuring that the environment is ready for testing. After the test completes, the container is removed in the DisposeAsync method.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
public Task InitializeAsync()
{
    return _mongoDbContainer.StartAsync();
}

public Task DisposeAsync()
{
    return _mongoDbContainer.DisposeAsync().AsTask();
}

[Fact]
[Trait(nameof(DockerCli.DockerPlatform), nameof(DockerCli.DockerPlatform.Linux))]
public void ConnectionStateReturnsOpen()
{
    // Given
    var client = new MongoClient(_mongoDbContainer.GetConnectionString());

    // When
    using var databases = client.ListDatabases();

    // Then
    Assert.Contains(databases.ToEnumerable(), database => database.TryGetValue("name", out var name) && "admin".Equals(name.AsString));
}

[Fact]
[Trait(nameof(DockerCli.DockerPlatform), nameof(DockerCli.DockerPlatform.Linux))]
public async Task ExecScriptReturnsSuccessful()
{
    // Given
    const string scriptContent = "printjson(db.adminCommand({listDatabases:1,nameOnly:true,filter:{\"name\":/^admin/}}));";

    // When
    var execResult = await _mongoDbContainer.ExecScriptAsync(scriptContent)
        .ConfigureAwait(true);

    // Then
    Assert.True(0L.Equals(execResult.ExitCode), execResult.Stderr);
    Assert.Empty(execResult.Stderr);
}

The test example uses the following NuGet dependencies:

1
2
3
4
5
<PackageReference Include="Microsoft.NET.Test.Sdk"/>
<PackageReference Include="coverlet.collector"/>
<PackageReference Include="xunit.runner.visualstudio"/>
<PackageReference Include="xunit"/>
<PackageReference Include="MongoDB.Driver"/>

To execute the tests, use the command dotnet test from a terminal.

Tip

For the complete source code of this example and additional information, please refer to our test projects.

MongoDb Replica Set

By default, MongoDB runs as a standalone instance. If your tests require a MongoDB replica set, use the following configuration which will initialize a single-node replica set:

1
2
3
4
5
6
7
8
[UsedImplicitly]
public sealed class MongoDbNamedReplicaSetConfiguration : MongoDbContainerTest
{
    public MongoDbNamedReplicaSetConfiguration()
        : base(new MongoDbBuilder().WithReplicaSet("rs1").Build(), true)
    {
    }
}