2

I need to run series of xUnit tests that depend on several Docker containers. I would prefer that xUnit takes care of the whole process - starting containers (similar to docker-compose env up), running tests and then tearing containers (i.e. docker-compose env down).

Is there support in Visual Studio or xUnit for this or this process needs to be manually implemented?

1 Answer 1

1

To do this without any extra dependencies, you can use Process.Start that emulates starting through command line. Here is class that wraps and provides this functionality:

public class DockerStarter : IDisposable
{
    private const string DOCKER_COMPOSE = @"c:\Program Files\Docker\Docker\resources\bin\docker-compose.exe";
    public string ComposeFile { get; set; }
    public string WorkingDir { get; set; }

    public DockerStarter(string composeFile, string workingDir)
    {
        ComposeFile = composeFile;
        WorkingDir = workingDir;
    }

    public void Start()
    {
        var startInfo = generateInfo("up");
        _dockerProcess = Process.Start(startInfo);
        // TODO: Find better way to wait for Docker containers to start
        Thread.Sleep(1000);
    }

    private Process _dockerProcess;

    public void Dispose()
    {
        _dockerProcess.Close();

        var stopInfo = generateInfo("down");
        var stop = Process.Start(stopInfo);
        stop.WaitForExit();
    }

    private ProcessStartInfo generateInfo(string argument)
    {
        var procInfo = new ProcessStartInfo
        {
            FileName = DOCKER_COMPOSE,
            Arguments = $"-f {ComposeFile} {argument}",
            WorkingDirectory = WorkingDir
        };
        return procInfo;
    }
}

Obviously there are downsides to this approach:

  • Fixed path to docker-compose executable
  • Manual wait on container start

I'll see if there is better way to directly interact with Docker daemon and update answer if possible.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.