在容器中執行 .NET 測試
目錄
先決條件
完成本指南的所有先前章節,從 將 .NET 應用程式容器化 開始。
概述
測試是現代軟體開發的重要組成部分。測試對不同的開發團隊來說可能意味著很多事情。有單元測試、整合測試和端到端測試。在本指南中,您將瞭解在開發和建置時如何在 Docker 中執行單元測試。
在本地開發時執行測試
範例應用程式已在 `tests` 目錄中包含一個 xUnit 測試。在本地開發時,您可以使用 Compose 來執行測試。
在 `docker-dotnet-sample` 目錄中執行以下命令,以在容器內執行測試。
$ docker compose run --build --rm server dotnet test /source/tests
您應該會看到包含以下內容的輸出。
Starting test execution, please wait...
A total of 1 test files matched the specified pattern.
Passed! - Failed: 0, Passed: 1, Skipped: 0, Total: 1, Duration: < 1 ms - /source/tests/bin/Debug/net6.0/tests.dll (net6.0)
要瞭解更多關於此命令的資訊,請參閱 docker compose run。
建置時執行測試
要在建置時執行測試,您需要更新 Dockerfile。您可以建立一個新的測試階段來執行測試,或在現有的建置階段中執行測試。在本指南中,請更新 Dockerfile 以在建置階段中執行測試。
以下是更新後的 Dockerfile。
# syntax=docker/dockerfile:1
FROM --platform=$BUILDPLATFORM mcr.microsoft.com/dotnet/sdk:6.0-alpine AS build
ARG TARGETARCH
COPY . /source
WORKDIR /source/src
RUN --mount=type=cache,id=nuget,target=/root/.nuget/packages \
dotnet publish -a ${TARGETARCH/amd64/x64} --use-current-runtime --self-contained false -o /app
RUN dotnet test /source/tests
FROM mcr.microsoft.com/dotnet/sdk:6.0-alpine AS development
COPY . /source
WORKDIR /source/src
CMD dotnet run --no-launch-profile
FROM mcr.microsoft.com/dotnet/aspnet:6.0-alpine AS final
WORKDIR /app
COPY --from=build /app .
ARG UID=10001
RUN adduser \
--disabled-password \
--gecos "" \
--home "/nonexistent" \
--shell "/sbin/nologin" \
--no-create-home \
--uid "${UID}" \
appuser
USER appuser
ENTRYPOINT ["dotnet", "myWebApp.dll"]
執行以下命令以使用建置階段作為目標來建置映像並檢視測試結果。 包含 `--progress=plain` 以檢視建置輸出,`--no-cache` 以確保始終執行測試,以及 `--target build` 以鎖定建置階段為目標。
$ docker build -t dotnet-docker-image-test --progress=plain --no-cache --target build .
您應該會看到包含以下內容的輸出。
#11 [build 5/5] RUN dotnet test /source/tests
#11 1.564 Determining projects to restore...
#11 3.421 Restored /source/src/myWebApp.csproj (in 1.02 sec).
#11 19.42 Restored /source/tests/tests.csproj (in 17.05 sec).
#11 27.91 myWebApp -> /source/src/bin/Debug/net6.0/myWebApp.dll
#11 28.47 tests -> /source/tests/bin/Debug/net6.0/tests.dll
#11 28.49 Test run for /source/tests/bin/Debug/net6.0/tests.dll (.NETCoreApp,Version=v6.0)
#11 28.67 Microsoft (R) Test Execution Command Line Tool Version 17.3.3 (x64)
#11 28.67 Copyright (c) Microsoft Corporation. All rights reserved.
#11 28.68
#11 28.97 Starting test execution, please wait...
#11 29.03 A total of 1 test files matched the specified pattern.
#11 32.07
#11 32.08 Passed! - Failed: 0, Passed: 1, Skipped: 0, Total: 1, Duration: < 1 ms - /source/tests/bin/Debug/net6.0/tests.dll (net6.0)
#11 DONE 32.2s
摘要
在本節中,您學習了如何在本地開發時使用 Compose 執行測試,以及如何在建置映像時執行測試。
相關資訊
後續步驟
接下來,您將學習如何使用 GitHub Actions 設定 CI/CD 流程。