Search code examples
c#e2e-testingtestcontainers

Creating a Container from ImageFromDockerfileBuilder with TestContainers .NET C#


I'm taking a stab at using the TestContainers package for my .NET application. I have a Dockerfile authored for building the image that I need for my application. I followed the instructions on the documentation:

var image = new ImageFromDockerfileBuilder()
    .WithDockerfileDirectory(CommonDirectoryPath.GetSolutionDirectory(), string.Empty)
    .WithDockerfile("Dockerfile")
    .Build();

await image.CreateAsync().ConfigureAwait(false);

However, I'm unsure how to create and run a container using this newly built image. The CreateAsync() call does not return a value and image is indicating that is an IFutureDockerImage. I do see a new image being created locally in Docker Desktop after the CreateAsync() call completes.


Solution

  • The WithImage() method on ContainerBuilder accepts the IFutureDockerImage type that gets returned from calling on ImageFromDockerfileBuilder.Build().

    public static async Task<IContainer> CreateAndStartDatabaseContainer()
    {
        var image = new ImageFromDockerfileBuilder()
            .WithDockerfileDirectory(CommonDirectoryPath.GetSolutionDirectory(), string.Empty)
            .WithDockerfile("Dockerfile")
            .Build();
    
        await image.CreateAsync().ConfigureAwait(false);
    
        var container = new ContainerBuilder()
            .WithImage(image)
            .WithPortBinding(9153, 3306)
            .WithEnvironment("stage", "e2e")
            .Build();
    
        await container.StartAsync().ConfigureAwait(false);
        return container;
    }