You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

多阶段Docker容器运行C#测试问题:拆分阶段后dotnet test无输出

解决多阶段Docker构建中dotnet test无输出退出的问题

问题根源

拆分构建与测试阶段后,仅复制测试项目的源码目录会缺失dotnet test --no-build必需的关键文件:

  • 测试项目编译生成的bin/、obj/目录(包含可执行的测试程序集)
  • 测试项目依赖的其他项目(如主应用)的构建输出
  • 还原完成的NuGet包缓存(可选,可避免重复执行restore)

缺少这些文件时,dotnet test无法找到可执行的测试程序或依赖组件,会静默退出且无任何输出。


解决方案

方案一:复制完整构建产物(适配多项目依赖场景)

修改测试阶段的COPY指令,复制测试项目的完整目录(含build阶段生成的bin/obj),若测试项目依赖主项目,同步复制主项目的构建输出:

FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
COPY ./ ./
RUN dotnet restore ./mysln.sln -r linux-x64
# 构建整个解决方案,确保所有依赖项目完成编译
RUN dotnet build ./mysln.sln --configuration Release

FROM mcr.microsoft.com/dotnet/sdk:6.0 AS tests
# 复制测试项目完整目录(包含bin/obj构建产物)
COPY --from=build ./tests/mytests/ ./tests/mytests/
# 若测试项目依赖主项目,复制主项目的Release构建输出(路径需根据实际项目调整)
COPY --from=build ./src/myapp/bin/Release/net6.0/linux-x64/ ./src/myapp/bin/Release/net6.0/linux-x64/

# 启用正常日志输出,便于排查问题
ENTRYPOINT ["dotnet", "test", "./tests/mytests/mytests.csproj", "--no-build", "--configuration Release", "-v n"]

方案二:使用dotnet publish打包测试项目(更精简镜像)

在build阶段通过dotnet publish将测试项目及所有依赖打包到统一目录,再复制到测试阶段,无需保留源码:

FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
COPY ./ ./
RUN dotnet restore ./mysln.sln -r linux-x64
# 发布测试项目,自动打包所有依赖到指定输出目录
RUN dotnet publish ./tests/mytests/mytests.csproj --configuration Release --output /app/test-output -r linux-x64

FROM mcr.microsoft.com/dotnet/sdk:6.0 AS tests
# 复制发布后的测试程序及全部依赖
COPY --from=build /app/test-output/ ./

# 直接运行打包后的测试程序集
ENTRYPOINT ["dotnet", "test", "./mytests.dll", "--no-build", "-v n"]

内容的提问来源于stack exchange,提问作者Shadow

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 02:55:45