Raj*_*roi 17 .net unit-testing
我们正在使用 Coverlets ( https://github.com/tonerdo/coverlet ) 在包含多个项目的 .NET 解决方案中测量单元测试的代码覆盖率。结果针对解决方案中的每个项目单独显示。我们想要的是整个解决方案的统一结果。任何人都可以建议获得它的最佳方法吗?如果有任何可能无法通过 Coverlet,您是否可以建议任何可以使用 CLI 执行此操作的替代开源工具。我们基本上需要将它与 CI 工具集成,如果覆盖率低于阈值,它应该发出警告。
Joe*_*eke 12
这就是我们使用 为整个解决方案生成代码覆盖率的方式coverlet.msbuild
。
coverlet.msbuild
在您的解决方案中的每个测试项目中引用。dotnet test {solution_filename.sln} --logger:trx --results-directory ../TestResults \
"/p:CollectCoverage=true" \
"/p:CoverletOutput=../TestResults/" \
"/p:MergeWith=../TestResults/coverlet.json" \
"/p:CoverletOutputFormat=\"json,cobertura\""
Run Code Online (Sandbox Code Playgroud)
如果在 Windows 上运行它,您可能需要对传入这些参数的某些字符进行转义,例如逗号 ( %2c
)。
为了合并多个项目的结果,我们生成了两种输出格式,json 和 cobertura。请参阅参数/p:CoverletOutputFormat
。
在为每个项目生成代码覆盖率时,coverlet 将/p:MergeWith
用于将当前项目的coverlet.json 与之前的coverlet.json 合并。
这种方法为解决方案生成了一个 cobertura 结果文件,我们稍后可以在 CI 构建中使用它。
小智 6
如果您使用coverage.collector,它将为每个项目生成单独的测试结果文件。
然后,您可以使用报告生成器工具将多个结果合并为一个。
以下是我们在 CI 中的做法:
dotnet test <solution-file> --collect:"XPlat Code Coverage"
dotnet tool install --global dotnet-reportgenerator-globaltool --version <version-number>
reportgenerator -reports:<base-directory>/**/coverage.cobertura.xml -targetdir:<output-directory>/CoverageReport -reporttypes:Cobertura
Run Code Online (Sandbox Code Playgroud)
这将为您的所有测试项目生成综合报告。
最近我遇到了同样的问题,乔尔的回答非常有效。除非你需要 xml 而不是 json。在这种情况下,您必须逐个运行测试项目,生成 json 输出并与前一个项目合并,但以您需要的格式运行最后一个项目。
这是我的做法的一个例子:
RUN dotnet test "tests/[project name].Test.Integration/[project name].Test.Integration.csproj" \
--configuration Release \
--no-restore \
--no-build \
--verbosity=minimal \
-p:CollectCoverage=true \
-p:CoverletOutputFormat="json" \
-p:CoverletOutput=/src/cover.json
RUN dotnet test "tests/[project name].Test.Unit/[project name].Test.Unit.csproj" \
--configuration Release \
--no-restore \
--no-build \
--verbosity=minimal \
-p:CollectCoverage=true \
-p:CoverletOutputFormat="opencover" \
-p:CoverletOutput=/src/cover.xml \
-p:MergeWith=../../cover.json
Run Code Online (Sandbox Code Playgroud)
我在 Docker 中运行它,我的文件夹结构可能看起来有点混乱 =)。为了避免任何混淆,这里是:
src
---src
---tests
------[project name].Test.Integration
---------[project name].Test.Integration.csproj
------[project name].Test.Unit
---------[project name].Test.Unit.csproj
---[project name].sln
---cover.json <- this file gets created after the first command
---cover.xml <- this file gets created after the second command
Run Code Online (Sandbox Code Playgroud)
因此,我首先运行集成测试的覆盖率,然后将其与所需格式的单元测试覆盖率合并(opencover,因为我需要它用于 SonarQube)