在容器中執行 .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
要了解有關構建和執行測試的更多資訊,請參閱 使用 Docker 構建指南。
總結
在本節中,你學習瞭如何在本地開發時使用 Compose 執行測試,以及如何在構建映象時執行測試。
相關資訊
下一步
接下來,你將學習如何使用 GitHub Actions 設定 CI/CD 管道。