如何在 docker 容器中运行 .NET 单元测试



我有一个包含MSTest单元测试的.NET Core应用程序。使用此 Dockerfile 执行所有测试的命令是什么?

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

文件夹结构为:

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

使用安装了 .NET Core SDK 的基础映像。例如:

microsoft/dotnet
microsoft/dotnet:1.1.2-sdk

如果没有 SDK,则无法在基于运行时的映像中运行dotnet test。这就是需要基于 SDK 的映像的原因。下面是一个完全可行的Dockerfile示例:

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命令在 docker 映像生成过程中执行。

ENTRYPOINT命令在 docker 容器启动时执行。

对于任何也在为这个问题苦苦挣扎但dotnet restore需要很长时间的人,我在下面创建了一个 Dockerfile 来为我解决这个问题:

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"]

注意:我没有在我的 Dockerfile 中包含RUN dotnet test,因为如果测试失败,这将停止构建,这不适合我的场景

我还有一个.dockerignore 文件,其中包含以下内容:

bin/
obj/

作为参考,这是我的文件夹结构:

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

最新更新