在容器中執行 .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/net8.0/tests.dll (net8.0)
要了解有關此命令的更多資訊,請參閱docker compose run。
構建時執行測試
要在構建時執行測試,你需要更新 Dockerfile。你可以建立一個新的測試階段來執行測試,或者在現有的構建階段執行測試。對於本指南,請更新 Dockerfile 以在構建階段執行測試。
以下是更新後的 Dockerfile。
# syntax=docker/dockerfile:1
FROM --platform=$BUILDPLATFORM mcr.microsoft.com/dotnet/sdk:8.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:8.0-alpine AS development
COPY . /source
WORKDIR /source/src
CMD dotnet run --no-launch-profile
FROM mcr.microsoft.com/dotnet/aspnet:8.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/net8.0/myWebApp.dll
#11 28.47 tests -> /source/tests/bin/Debug/net8.0/tests.dll
#11 28.49 Test run for /source/tests/bin/Debug/net8.0/tests.dll (.NETCoreApp,Version=v8.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/net8.0/tests.dll (net8.0)
#11 DONE 32.2s
摘要
在本節中,你學習瞭如何在本地開發時使用 Compose 執行測試,以及如何在構建映象時執行測試。
相關資訊
後續步驟
接下來,你將學習如何使用 GitHub Actions 設定 CI/CD 管道。