首页 > 解决方案 > 在本地开发期间在 Docker 中运行 .NET Core 测试

问题描述

我知道我们可以在 Docker 构建期间使用一个阶段来构建我们的 Dockerfile,以执行dotnet test和运行我们的单元测试。

我的问题是关于我们是否希望这些测试在本地开发期间运行(例如使用 Visual Studio)。

如果我们运行 (F5) 一个 .NET Core 应用程序,该应用程序设置为构建到 Docker 映像中,然后使用 Docker 的 VS 工具进行调试等,那么我们是否还会在那个时候每次都运行我们的单元测试我们在本地运行/调试?

如果我在开发/调试期间已经使用了 Visual Studio 内置的测试运行程序(甚至是 Live Unit Testing 功能)怎么办?如果我在 Dockerfile 中定义一个用于运行测试的阶段,我是否仍然被迫在 IDE 的 Run/F5 命令触发的 docker 构建期间运行相同的单元测试?

如果不是,那么在 Docker 中运行测试的推荐方法是什么,但只在 CI 构建期间而不是在本地开发构建期间执行该阶段?

标签: visual-studiodockerunit-testing.net-coreautomated-tests

解决方案


对我来说,在 Docker 环境之外直接通过 VS 运行测试项目是最有意义的,只要您的测试当然不需要在 Docker 环境中运行。然后让 CI 通过 Dockerfile 运行测试。

即使您的 Dockerfile 是使用每个 F5 构建的,您也不需要运行测试。在多阶段 Dockerfile 中,您不需要有单行阶段依赖项。我的意思是,您可以拥有一个纯选择加入且默认不运行的测试阶段。只有在运行时将目标阶段明确设置为测试阶段,它才会运行docker build。可以在此处找到有关此方法的更多详细信息:https ://github.com/dotnet/dotnet-docker/tree/main/samples/complexapp#running-tests-as-an-opt-in-stage 。这是一个示例 Dockerfile:

FROM mcr.microsoft.com/dotnet/core/sdk:3.1 AS build
WORKDIR /source

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

# copy and build app
COPY app/ app/
WORKDIR /source/app
RUN dotnet build -c release --no-restore

# test stage -- exposes optional entrypoint
# target entrypoint with: docker build --target test
FROM build AS test
WORKDIR /source/tests
COPY tests/ .
ENTRYPOINT ["dotnet", "test", "--logger:trx"]

FROM build AS publish
RUN dotnet publish -c release --no-build -o /app

# final stage/image
FROM mcr.microsoft.com/dotnet/core/runtime:3.1
WORKDIR /app
COPY --from=publish /app .
ENTRYPOINT ["dotnet", "app.dll"]

推荐阅读