-
-
Notifications
You must be signed in to change notification settings - Fork 340
feat: Introduce a new Testcontainers.Xunit package #1165
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
fd154c0
79e1ffe
b4b60e8
39df223
f675189
7289881
dc66835
181c812
610f7ba
85120de
bb58f4b
8de9b29
f06b8df
d7b0ec5
2c7a09b
e0a1bf8
77eab50
786801b
e8fa351
34d8a49
d9960df
45d2fc8
c47c30d
7aa2067
a2151a7
630a073
313b01e
4f8394f
3eb96b5
0793d06
285df3b
2e79dd7
53b6290
8a286b2
ea693d8
aeb8cd5
250d6a4
5448078
80b1f1d
df9eb0f
b77a426
7717214
ef3b269
64ce5b7
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,109 @@ | ||
| # Testing with xUnit.net | ||
|
|
||
| The [Testcontainers.Xunit](https://www.nuget.org/packages/Testcontainers.Xunit) package simplifies writing tests with containers in [xUnit.net](https://xunit.net). By leveraging xUnit.net's [shared context](https://xunit.net/docs/shared-context), this package automates the setup and teardown of test resources, creating and disposing of containers as needed. This reduces repetitive code and avoids common patterns that developers would otherwise need to implement repeatedly. | ||
|
|
||
| To get started, add the following dependency to your project file: | ||
|
|
||
| ```shell title="NuGet" | ||
| dotnet add package Testcontainers.Xunit | ||
| ``` | ||
|
|
||
| ## Creating an isolated test context | ||
|
|
||
| To create a new test resource instance for each test, inherit from the `ContainerTest<TBuilderEntity, TContainerEntity>` class. Each test resource instance is isolated and not shared across other tests, making this approach ideal for destructive operations that could interfere with other tests. You can access the generic `TContainerEntity` container instance through the `Container` property. | ||
|
|
||
| The example below demonstrates how to override the `Configure(TBuilderEntity)` method and pin the image version. This method allows you to configure the container instance specifically for your test case, with all container builder methods available. If your tests rely on a Testcontainers' module, the module's default configurations will be applied. | ||
|
|
||
| === "Configure a Redis Container" | ||
| ```csharp | ||
| --8<-- "tests/Testcontainers.Xunit.Tests/RedisContainerTest`1.cs:ConfigureRedisContainer" | ||
| ``` | ||
|
|
||
| !!!tip | ||
| Always pin the image version to avoid flakiness. This ensures consistency and prevents unexpected behavior, as the `latest` tag may pointing to a new version. | ||
|
|
||
| The base class also receives an instance of xUnit.net's [ITestOutputHelper](https://xunit.net/docs/capturing-output) to capture and forward log messages to the running test. | ||
|
|
||
| Considering that xUnit.net runs tests in a deterministic natural sort order (like `Test1`, `Test2`, etc.), retrieving the Redis (string) value in the second test will always return `null` since a new test resource instance (Redis container) is created for each test. | ||
|
|
||
| === "Run Tests" | ||
| ```csharp | ||
| --8<-- "tests/Testcontainers.Xunit.Tests/RedisContainerTest`1.cs:RunTests" | ||
| ``` | ||
|
|
||
| If you check the output of `docker ps`, you will notice that three container instances in total are run, with two of them being Redis instances. | ||
|
|
||
| ```title="List running containers" | ||
| PS C:\Sources\dotnet\testcontainers-dotnet> docker ps | ||
| CONTAINER ID IMAGE COMMAND CREATED | ||
| be115f3df138 redis:7.0 "docker-entrypoint.s…" 3 seconds ago | ||
| 59349127f8c0 redis:7.0 "docker-entrypoint.s…" 4 seconds ago | ||
| 45fa02b3e997 testcontainers/ryuk:0.9.0 "/bin/ryuk" 4 seconds ago | ||
| ``` | ||
|
|
||
| ## Creating a shared test context | ||
|
|
||
| Sometimes, creating and disposing of a test resource can be an expensive operation that you do not want to repeat for every test. By inheriting from the `ContainerFixture<TBuilderEntity, TContainerEntity>` class, you can share the test resource instance across all tests within the same test class. | ||
|
|
||
| xUnit.net's fixture implementation does not rely on the `ITestOutputHelper` interface to capture and forward log messages; instead, it expects an implementation of `IMessageSink`. Make sure your fixture's default constructor accepts the interface implementation and forwards it to the base class. | ||
|
|
||
| === "Configure Redis Container" | ||
| ```csharp | ||
| --8<-- "tests/Testcontainers.Xunit.Tests/RedisContainerTest`2.cs:ConfigureRedisContainer" | ||
| ``` | ||
|
|
||
| This ensures that the fixture is created only once for the entire test class, which also improves overall test performance. You must implement the `IClassFixture<TFixture>` interface with the previously created container fixture type in your test class and add the type as argument to the default constructor. | ||
|
|
||
| === "Inject Redis Container" | ||
| ```csharp | ||
| --8<-- "tests/Testcontainers.Xunit.Tests/RedisContainerTest`2.cs:InjectContainerFixture" | ||
| ``` | ||
|
|
||
| In this case, retrieving the Redis (string) value in the second test will no longer return `null`. Instead, it will return the value added in the first test. | ||
|
|
||
| === "Run Tests" | ||
| ```csharp | ||
| --8<-- "tests/Testcontainers.Xunit.Tests/RedisContainerTest`2.cs:RunTests" | ||
| ``` | ||
|
|
||
| The output of `docker ps` shows that, instead of two Redis containers, only one runs. | ||
|
|
||
| ```title="List running containers" | ||
| PS C:\Sources\dotnet\testcontainers-dotnet> docker ps | ||
| CONTAINER ID IMAGE COMMAND CREATED | ||
| d29a393816ce redis:7.0 "docker-entrypoint.s…" 3 seconds ago | ||
| e878f0b8f4bc testcontainers/ryuk:0.9.0 "/bin/ryuk" 3 seconds ago | ||
| ``` | ||
|
|
||
| ## Testing ADO.NET services | ||
|
|
||
| In addition to the two mentioned base classes, the package contains two more classes: `DbContainerTest` and `DbContainerFixture`, which behave identically but offer additional convenient features when working with services accessible through an ADO.NET provider. | ||
|
|
||
| Inherit from either the `DbContainerTest` or `DbContainerFixture` class and override the `Configure(TBuilderEntity)` method to configure your database service. | ||
|
|
||
| In this example, we use the default configuration of the PostgreSQL module. The container image capabilities are used to instantiate the database, schema, and test data. During startup, the PostgreSQL container runs SQL scripts placed under the `/docker-entrypoint-initdb.d/` directory automatically. | ||
|
|
||
| === "Configure PostgreSQL Container" | ||
| ```csharp | ||
| --8<-- "tests/Testcontainers.Xunit.Tests/PostgreSqlContainer.cs:ConfigurePostgreSqlContainer" | ||
| ``` | ||
|
|
||
| Inheriting from the database container test or fixture class requires you to implement the abstract `DbProviderFactory` property and resolve a compatible `DbProviderFactory` according to your ADO.NET service. | ||
|
|
||
| === "Configure DbProviderFactory" | ||
| ```csharp | ||
| --8<-- "tests/Testcontainers.Xunit.Tests/PostgreSqlContainer.cs:ConfigureDbProviderFactory" | ||
| ``` | ||
|
|
||
| !!! note | ||
|
|
||
| Depending on how you initialize and access the database, it may be necessary to override the `ConnectionString` property and replace the default database name with the one actual in use. | ||
|
|
||
| After configuring the dependent ADO.NET service, you can add the necessary tests. In this case, we run an SQL `SELECT` statement to retrieve the first record from the `album` table. | ||
|
|
||
| === "Run Tests" | ||
| ```csharp | ||
| --8<-- "tests/Testcontainers.Xunit.Tests/PostgreSqlContainer.cs:RunTests" | ||
| ``` | ||
|
|
||
| --8<-- "docs/modules/_call_out_test_projects.txt" |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| root = true |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,15 @@ | ||
| namespace Testcontainers.Xunit; | ||
|
|
||
| /// <summary> | ||
| /// Fixture for sharing a container instance across multiple tests in a single class. | ||
| /// See <a href="https://xunit.net/docs/shared-context">Shared Context between Tests</a> from xUnit.net documentation for more information about fixtures. | ||
| /// A logger is automatically configured to write diagnostic messages to xUnit's <see cref="IMessageSink" />. | ||
| /// </summary> | ||
| /// <param name="messageSink">An optional <see cref="IMessageSink" /> where the logs are written to. Pass <c>null</c> to ignore logs.</param> | ||
| /// <typeparam name="TBuilderEntity">The builder entity.</typeparam> | ||
| /// <typeparam name="TContainerEntity">The container entity.</typeparam> | ||
| [PublicAPI] | ||
| public class ContainerFixture<TBuilderEntity, TContainerEntity>(IMessageSink messageSink) | ||
| : ContainerLifetime<TBuilderEntity, TContainerEntity>(new MessageSinkLogger(messageSink)) | ||
| where TBuilderEntity : IContainerBuilder<TBuilderEntity, TContainerEntity>, new() | ||
| where TContainerEntity : IContainer; |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,91 @@ | ||
| namespace Testcontainers.Xunit; | ||
|
|
||
| /// <summary> | ||
| /// Base class managing the lifetime of a container. | ||
| /// </summary> | ||
| /// <typeparam name="TBuilderEntity">The builder entity.</typeparam> | ||
| /// <typeparam name="TContainerEntity">The container entity.</typeparam> | ||
| public abstract class ContainerLifetime<TBuilderEntity, TContainerEntity> : IAsyncLifetime | ||
| where TBuilderEntity : IContainerBuilder<TBuilderEntity, TContainerEntity>, new() | ||
| where TContainerEntity : IContainer | ||
| { | ||
| private readonly Lazy<TContainerEntity> _container; | ||
|
|
||
| [CanBeNull] | ||
| private ExceptionDispatchInfo _exception; | ||
|
|
||
| protected ContainerLifetime(ILogger logger) | ||
| { | ||
| _container = new Lazy<TContainerEntity>(() => Configure(new TBuilderEntity().WithLogger(logger)).Build()); | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Gets the container instance. | ||
| /// </summary> | ||
| public TContainerEntity Container | ||
| { | ||
| get | ||
| { | ||
| _exception?.Throw(); | ||
| return _container.Value; | ||
| } | ||
| } | ||
|
|
||
| /// <inheritdoc /> | ||
| LifetimeTask IAsyncLifetime.InitializeAsync() => InitializeAsync(); | ||
|
|
||
| #if !XUNIT_V3 | ||
| /// <inheritdoc /> | ||
| LifetimeTask IAsyncLifetime.DisposeAsync() => DisposeAsync(); | ||
| #else | ||
| /// <inheritdoc /> | ||
| LifetimeTask IAsyncDisposable.DisposeAsync() => DisposeAsync(); | ||
| #endif | ||
|
|
||
| /// <summary> | ||
| /// Extension method to further configure the container instance. | ||
| /// </summary> | ||
| /// <example> | ||
| /// <code> | ||
| /// public class MariaDbRootUserFixture(IMessageSink messageSink) : DbContainerFixture<MariaDbBuilder, MariaDbContainer>(messageSink) | ||
| /// { | ||
| /// public override DbProviderFactory DbProviderFactory => MySqlConnectorFactory.Instance; | ||
| /// <br /> | ||
| /// protected override MariaDbBuilder Configure(MariaDbBuilder builder) | ||
| /// { | ||
| /// return builder.WithUsername("root"); | ||
| /// } | ||
| /// } | ||
| /// </code> | ||
| /// </example> | ||
| /// <param name="builder">The container builder to configure.</param> | ||
| /// <returns>A configured instance of <typeparamref name="TBuilderEntity" />.</returns> | ||
| protected virtual TBuilderEntity Configure(TBuilderEntity builder) | ||
| { | ||
| return builder; | ||
| } | ||
|
|
||
| /// <inheritdoc cref="IAsyncLifetime" /> | ||
| protected virtual async LifetimeTask InitializeAsync() | ||
| { | ||
| try | ||
| { | ||
| await Container.StartAsync() | ||
| .ConfigureAwait(false); | ||
| } | ||
| catch (Exception e) | ||
| { | ||
| _exception = ExceptionDispatchInfo.Capture(e); | ||
| } | ||
| } | ||
|
|
||
| /// <inheritdoc cref="IAsyncLifetime" /> | ||
| protected virtual async LifetimeTask DisposeAsync() | ||
| { | ||
| if (_exception == null) | ||
| { | ||
| await Container.DisposeAsync() | ||
| .ConfigureAwait(false); | ||
| } | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,18 @@ | ||
| namespace Testcontainers.Xunit; | ||
|
|
||
| /// <summary> | ||
| /// Base class for tests needing a container per test method. | ||
| /// A logger is automatically configured to write messages to xUnit's <see cref="ITestOutputHelper" />. | ||
| /// </summary> | ||
| /// <param name="testOutputHelper">An optional <see cref="ITestOutputHelper" /> where the logs are written to. Pass <c>null</c> to ignore logs.</param> | ||
| /// <param name="configure">An optional callback to configure the container.</param> | ||
| /// <typeparam name="TBuilderEntity">The builder entity.</typeparam> | ||
| /// <typeparam name="TContainerEntity">The container entity.</typeparam> | ||
| [PublicAPI] | ||
| public abstract class ContainerTest<TBuilderEntity, TContainerEntity>(ITestOutputHelper testOutputHelper, Func<TBuilderEntity, TBuilderEntity> configure = null) | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Why do we provide the There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I initially wrote it like that for no particular reason. We can probably get rid of it, if only for consistency with how it's done with There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Wait, I take that back, it's pretty convenient actually. For example: public abstract class MongoDbContainerTest(ITestOutputHelper testOutputHelper, Func<MongoDbBuilder, MongoDbBuilder> configure = null)
: ContainerTest<MongoDbBuilder, MongoDbContainer>(testOutputHelper, configure)
{
[Fact]
public void Test()
{
}
[UsedImplicitly]
public sealed class MongoDbDefaultConfiguration(ITestOutputHelper testOutputHelper)
: MongoDbContainerTest(testOutputHelper);
[UsedImplicitly]
public sealed class MongoDbNoAuthConfiguration(ITestOutputHelper testOutputHelper)
: MongoDbContainerTest(testOutputHelper, builder => builder.WithUsername(string.Empty).WithPassword(string.Empty));
[UsedImplicitly]
public sealed class MongoDbV5Configuration(ITestOutputHelper testOutputHelper)
: MongoDbContainerTest(testOutputHelper, builder => builder.WithImage("mongo:5.0"));
[UsedImplicitly]
public sealed class MongoDbV4Configuration(ITestOutputHelper testOutputHelper)
: MongoDbContainerTest(testOutputHelper, builder => builder.WithImage("mongo:4.4"));
}There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This is probably an interesting use case, indeed. We should document it somehow, otherwise no one will know about the overload. |
||
| : ContainerLifetime<TBuilderEntity, TContainerEntity>(new TestOutputLogger(testOutputHelper)) | ||
| where TBuilderEntity : IContainerBuilder<TBuilderEntity, TContainerEntity>, new() | ||
| where TContainerEntity : IContainer | ||
| { | ||
| protected override TBuilderEntity Configure(TBuilderEntity builder) => configure != null ? configure(builder) : builder; | ||
| } | ||
Uh oh!
There was an error while loading. Please reload this page.