Thiago Silva
Thiago Silva

Reputation: 17711

Running tests for .NET Core in Docker during local dev

I understand that we can build our Dockerfile with a stage to execute dotnet test and run our unit tests during the docker build.

My question is regarding whether or not we would want those tests to run during local dev (e.g. with Visual Studio).

If we run (F5) a .NET Core app that is set up to build into a Docker image, and then use the VS tools for Docker to debug, etc., are we going to also be running our unit tests at that point EVERYTIME we run/debug locally?

What if I already use the test runner built-into Visual Studio (or even the Live Unit Testing feature) during dev/debug time? Am I still forced to run those same unit tests during the docker build that is triggered from the IDE's Run/F5 command if I define a stage in the Dockerfile for running tests?

If not, what is the recommended approach to running tests in Docker but only execute that stage during a CI build and not during a local dev build?

Upvotes: 4

Views: 4513

Answers (1)

Matt Thalman
Matt Thalman

Reputation: 3975

To me, it would make the most sense to run the test project directly by VS outside the context of Docker, as long as your tests do not require being run in a Docker environment of course. And then have CI run tests via the Dockerfile.

Even if your Dockerfile is built with every F5, you don't need to have the tests run. In a multi-stage Dockerfile you don't need to have a single line of stage dependencies. By that I mean, you can have a test stage that is purely opt-in and is not run by default. It would only be run if you explicitly set the target stage as the test stage when running docker build. More details on this approach can be found here: https://github.com/dotnet/dotnet-docker/tree/main/samples/complexapp#running-tests-as-an-opt-in-stage. Here's an example Dockerfile:

FROM mcr.microsoft.com/dotnet/core/sdk:3.1 AS build
WORKDIR /source

# copy csproj and restore as distinct layers
COPY app/*.csproj app/
RUN dotnet restore app/app.csproj

# copy and build app
COPY app/ app/
WORKDIR /source/app
RUN dotnet build -c release --no-restore

# test stage -- exposes optional entrypoint
# target entrypoint with: docker build --target test
FROM build AS test
WORKDIR /source/tests
COPY tests/ .
ENTRYPOINT ["dotnet", "test", "--logger:trx"]

FROM build AS publish
RUN dotnet publish -c release --no-build -o /app

# final stage/image
FROM mcr.microsoft.com/dotnet/core/runtime:3.1
WORKDIR /app
COPY --from=publish /app .
ENTRYPOINT ["dotnet", "app.dll"]

Upvotes: 6

Related Questions