Babak Fakhriloo
Babak Fakhriloo

Reputation: 2126

Build and run a docker container as a part of integration test in asp.net core

I have integration tests for my asp.net core 3.1 app which runs HostedService. As a part of integrations tests process, I want to build a docker container before tests start. I tried to add following command in test project config :

<Target Name="Test" AfterTargets="Build">
        <Exec command="docker run --rm -p 3030:3030 -v $PWD/mocks:/app/mocks dotronglong/faker:stable" />
</Target>

It returned "exited with code 127", so I changed it to be :

<Target Name="Test" AfterTargets="Build">
        <Exec command="C:\Program Files\Docker\Docker\resources\bin\docker run --rm -p 3030:3030 -v $PWD/mocks:/app/mocks dotronglong/faker:stable" />
</Target>

And I got "exited with code 9009".

This docker container has a dependency on "mocks" so I have set the project to have :

<ItemGroup>
      <None Update="mocks\api.json">
        <CopyToOutputDirectory>Always</CopyToOutputDirectory>
      </None>
</ItemGroup>

Overall, is it a correct way of running a docker container for integration test ? Consider that this test will be run in a CI/CD so the path used for running docker is also important.

Upvotes: 1

Views: 866

Answers (1)

You can use Docker.DotNet for create and run a container from a docker image. For create container:

var address = Environment.OSVersion.Platform == PlatformID.Unix
            ? new Uri("unix:///var/run/docker.sock")
            : new Uri("npipe://./pipe/docker_engine");

var config = new DockerClientConfiguration(address);
var dockerClient = config.CreateClient();

await dockerClient.Containers.CreateContainerAsync(
            new CreateContainerParameters
            {
                Image = "image_name",
                Name = "container_name"
            });

Then you can start container:

await dockerClient.Containers.StartContainerAsync("container_name", new ContainerStartParameters { });

See here for more information.

Upvotes: 1

Related Questions