|
| 1 | +# Testing with xUnit |
| 2 | + |
| 3 | +The [Testcontainers.Xunit](https://www.nuget.org/packages/Testcontainers.Xunit) package provides classes that simplify writing tests using Docker containers with [xUnit](https://xunit.net). Starting and disposing containers is handled automatically. Setting up logging is straightforward. |
| 4 | + |
| 5 | +## Use a container per test method |
| 6 | + |
| 7 | +If you need a fresh contaner per test method, inherit `ContainerTest<TBuilderEntity, TContainerEntity>` and use its `Container` property. |
| 8 | + |
| 9 | +```csharp |
| 10 | +using System.Threading.Tasks; |
| 11 | +using StackExchange.Redis; |
| 12 | +using Testcontainers.Redis; |
| 13 | +using Testcontainers.Xunit; |
| 14 | +using Xunit; |
| 15 | +using Xunit.Abstractions; |
| 16 | + |
| 17 | +namespace MyProject.Tests; |
| 18 | + |
| 19 | +public sealed class RedisContainerTest(ITestOutputHelper output) |
| 20 | + : ContainerTest<RedisBuilder, RedisContainer>(output) |
| 21 | +{ |
| 22 | + protected override RedisBuilder Configure(RedisBuilder builder) |
| 23 | + { |
| 24 | + // 👇 Pin the Redis image to version 7.4.0 (alpine) |
| 25 | + return builder.WithImage("redis:7.4.0-alpine"); |
| 26 | + } |
| 27 | + |
| 28 | + [Fact] |
| 29 | + public async Task Test1() |
| 30 | + { |
| 31 | + // 👆 A new fresh container is started before the test is run |
| 32 | +
|
| 33 | + // 👇 get the connection string from the container |
| 34 | + var connectionString = Container.GetConnectionString(); |
| 35 | + using var redis = ConnectionMultiplexer.Connect(connectionString); |
| 36 | + await redis.GetDatabase().StringSetAsync("key", "value"); |
| 37 | + |
| 38 | + // 👇 The container is disposed after the test has finished running |
| 39 | + } |
| 40 | + |
| 41 | + [Fact] |
| 42 | + public async Task Test2() |
| 43 | + { |
| 44 | + // 👆 Another fresh container is started before the second test is run |
| 45 | +
|
| 46 | + var connectionString = Container.GetConnectionString(); |
| 47 | + using var redis = ConnectionMultiplexer.Connect(connectionString); |
| 48 | + string value = await redis.GetDatabase().StringGetAsync("key"); |
| 49 | + Assert.Null(value); // 👈 value is null since the container is not shared |
| 50 | +
|
| 51 | + // 👇 The container is disposed after the test has finished running |
| 52 | + } |
| 53 | +} |
| 54 | +``` |
| 55 | + |
| 56 | +Injecting a `ITestOutputHelper` allows Testcontainers logs to be printed into the test runner output. |
| 57 | + |
| 58 | +## Use a container per test class |
| 59 | + |
| 60 | +Using a container per test method might be too heavy, especially if the container is slow to start. You might want to share a single container across all tests of a single class by using the `ContainerFixture<TBuilderEntity, TContainerEntity>` class that can be injected into your test classes. |
| 61 | + |
| 62 | +```csharp |
| 63 | +// TODO: sample code |
| 64 | +``` |
| 65 | + |
0 commit comments