ddcc3432
ddcc3432

Reputation: 479

How to run .NET unit tests in a docker container

I have a .NET Core application containing MSTest unit tests. What would the command be to execute all tests using this Dockerfile?

FROM microsoft/dotnet:1.1-runtime
ARG source
COPY . .
ENTRYPOINT ["dotnet", "test", "Unittests.csproj"]

Folder structure is:

/Dockerfile
/Unittests.csproj
/tests/*.cs

Upvotes: 10

Views: 31015

Answers (2)

Ilya Chumakov
Ilya Chumakov

Reputation: 25019

Use a base image with .NET Core SDK installed. For example:

microsoft/dotnet
microsoft/dotnet:1.1.2-sdk

You can't run dotnet test in a Runtime-based image without SDK. This is why an SDK-based image is required. Here is a fully-workable Dockerfile example:

FROM microsoft/dotnet

WORKDIR /app
COPY . .

RUN dotnet restore

# run tests on docker build
RUN dotnet test

# run tests on docker run
ENTRYPOINT ["dotnet", "test"]

RUN commands are executed during a docker image build process.

ENTRYPOINT command is executed when a docker container starts.

Upvotes: 23

Ciara Houlihan
Ciara Houlihan

Reputation: 31

For anyone who is also struggling with this question but dotnet restore is taking a very long time, I created a Dockerfile below that solved this issue for me:

FROM mcr.microsoft.com/dotnet/sdk:5.0
WORKDIR /App

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

# Copy everything else and build
COPY ./test ./
RUN dotnet publish -c Release -o out

# run tests on docker run
ENTRYPOINT ["dotnet", "test"]

Note: I didn't include RUN dotnet test in my Dockerfile as this would stop the build if the tests failed and this did not suit my scenario

I also had a .dockerignore file with the following contents:

bin/
obj/

For reference, this was my folder structure:

/bin/
/obj/
/test/*.cs
/.dockerignore
/Dockerfile
/testing.csproj

Upvotes: 1

Related Questions