首页 > 解决方案 > 对需要 Docker 的 .NET Core 应用程序进行单元测试

问题描述

我有一个 .NET Core 项目和一个 xUnit 项目来测试它。

后来我在我的主要 .NET Core 项目中添加了对 Docker 的支持。我以 Linux 为目标,并在我的 Docker 文件中添加了一堆操作。我的 Docker 映像托管在 Docker Desktop for Windows 上。我的项目现在需要在 Docker Linux 上运行,因为它引用了我在 Docker 文件中添加的资源。

我对如何处理我的 xUnit 项目感到困惑。我应该向它添加 Docker 支持吗?我不想将我的主项目的 Docker 文件的内容复制到 xUnit 的 Docker 文件,因为它可能会发生变化,并且它会构建一个对于单元项目来说不必要的大图像。

我可以从我的 xUnit 图像中调用我的主项目的图像吗?或者我可以不向我的单元项目添加对 Docker 的支持吗?

谢谢!

PS:我在 Windows 上使用 Visual Studio 2019

标签: .netdocker.net-corexunit

解决方案


您可以像往常一样从 Visual Studio 或直接在构建管道中运行它们dotnet test

但在我看来,更好的方法是在中间 docker 映像(构建映像)中运行它们,以确保您的应用程序也在 docker 上下文中运行,只需dotnet test在其中调用即可

有据可查的示例: 在 docker 中运行 dotnet 测试(第 5 步)

FROM mcr.microsoft.com/dotnet/core/sdk:3.0-alpine AS build
WORKDIR /app
COPY *.sln .
COPY src/Example.Service/*.csproj ./src/Example.Service/
COPY test/Example.Service.UnitTest/*.csproj ./test/Example.Service.UnitTest/
COPY test/Example.Service.ComponentTest/*.csproj ./test/Example.Service.ComponentTest/
RUN dotnet restore
# copy full solution over
COPY . .
RUN dotnet build
FROM build AS testrunner
WORKDIR /app/test/Example.Service.UnitTest
CMD ["dotnet", "test", "--logger:trx"]
# run the unit tests
FROM build AS test
WORKDIR /app/test/Example.Service.UnitTest
RUN dotnet test --logger:trx
# run the component tests
FROM build AS componenttestrunner
WORKDIR /app/test/Example.Service.ComponentTest
CMD ["dotnet", "test", "--logger:trx"]
# publish the API
FROM build AS publish
WORKDIR /app/src/Example.Service
RUN dotnet publish -c Release -o out
# run the api
FROM mcr.microsoft.com/dotnet/core/aspnet:3.0-alpine AS runtime
WORKDIR /app
COPY --from=publish /app/src/Example.Service/out ./
EXPOSE 80
ENTRYPOINT ["dotnet", "Example.Service.dll"]

推荐阅读