Run c# tests in multi-stage docker container

979 Views Asked by At

I have following dockerfile which runs my tests:

FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
COPY ./ ./
RUN dotnet restore ./mysln.sln -r linux-x64

RUN dotnet build ./tests/mytests/mytests.csproj
ENTRYPOINT ["dotnet", "test", "./tests/mytests/mytests.csproj", "--no-build"]

I'd like to split build and test step, so I don't have entire codebase with obj/bin files in my image (which is executed later, and can be executed multiple times, so there is no reason to build it each time).

For instance:

FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
COPY ./ ./
RUN dotnet restore ./mysln.sln -r linux-x64

RUN dotnet build ./tests/mytests/mytests.csproj

FROM mcr.microsoft.com/dotnet/sdk:6.0 AS tests

COPY --from=build ./tests/mytests/ ./tests/mytests/

ENTRYPOINT ["dotnet", "test", "./tests/mytests/mytests.csproj", "--no-build"]

However this does not work for some reason, dotnet test does nothing (no error reported, no std out) - just quits, even though it's running in target image.

1

There are 1 best solutions below

0
On

Your test stage is based on the sdk:6.0 tag, not taking advantage of the copying and build you've already done in your build stage. I would recommend the following:

Instead of: FROM mcr.microsoft.com/dotnet/sdk:6.0 AS tests

Use this: FROM build AS tests

Edit: Also should remove this line: COPY --from=build ./tests/mytests/ ./tests/mytests/

This pattern is documented at https://github.com/dotnet/dotnet-docker/tree/36e083bb836a5f9a3444ef7ad4459e5c580a7984/samples/complexapp#running-tests-as-an-opt-in-stage