10

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
ddcc3432
  • 459
  • 1
  • 6
  • 16

2 Answers2

23

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.

Ilya Chumakov
  • 23,161
  • 9
  • 86
  • 114
  • 4
    Anyone know how to fail the build using the exit code from "Run dotnet test" – Jason Rowe Oct 30 '17 at 15:13
  • Can someone clarify what the "test" parameter is? is it the unit test method or the unit test project name, also a distinction between the Run and Entry point is needed. –  Nov 09 '17 at 22:52
  • 2
    @eschneider : the "test" parameter is a command line agrument for the "dotnet" command. Both `RUN` and `ENTRYPOINT` commands do the same thing at this Dockerfile. The difference is only *when* the tests are runned. https://docs.docker.com/engine/reference/builder/#entrypoint – Ilya Chumakov Nov 10 '17 at 05:29
  • So what indications are there that my unit tests are running in docker and for what image? Also does this work when I run from the test explorer? –  Nov 10 '17 at 21:00
  • 2
    @JasonRowe to make the build fail set Environment.Exit(yourCode) when your tests finish. Check for that exit code in your CI scripts. – ddcc3432 Dec 03 '17 at 23:17
1

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