在本地开发期间在 Docker 中运行 .NET Core 测试

Thi*_*lva 4 automated-tests unit-testing visual-studio docker .net-core

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

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

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

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

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

Mat*_*man 6

对我来说,在 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"]
Run Code Online (Sandbox Code Playgroud)