本篇會簡單講述使用 Coverlet 為專案取得測試覆蓋率。
首先,先在測試專案中,新增 coverlet.msbuild
套件:
# Location: ~/dotnet-sln
$ cd WebProj.Tests
# Location: ~/dotnet-sln/WebProj.Tests
$ dotnet add package coverlet.msbuild
Writing /var/folders/hx/lgdjx1l93pq08s35hhwb0py40000gn/T/tmpP3owm8.tmp
info : Adding PackageReference for package 'coverlet.msbuild' into project '/Users/ironman/dotnet-sln/WebProj.Tests/WebProj.Tests.csproj'.
info : Restoring packages for /Users/ironman/dotnet-sln/WebProj.Tests/WebProj.Tests.csproj...
info : GET https://api.nuget.org/v3-flatcontainer/coverlet.msbuild/index.json
info : OK https://api.nuget.org/v3-flatcontainer/coverlet.msbuild/index.json 1305ms
info : Package 'coverlet.msbuild' is compatible with all the specified frameworks in project '/Users/ironman/dotnet-sln/WebProj.Tests/WebProj.Tests.csproj'.
info : PackageReference for package 'coverlet.msbuild' version '2.7.0' added to file '/Users/ironman/dotnet-sln/WebProj.Tests/WebProj.Tests.csproj'.
info : Committing restore...
info : Generating MSBuild file /Users/ironman/dotnet-sln/WebProj.Tests/obj/WebProj.Tests.csproj.nuget.g.props.
info : Generating MSBuild file /Users/ironman/dotnet-sln/WebProj.Tests/obj/WebProj.Tests.csproj.nuget.g.targets.
info : Writing assets file to disk. Path: /Users/ironman/dotnet-sln/WebProj.Tests/obj/project.assets.json
log : Restore completed in 1.79 sec for /Users/ironman/dotnet-sln/WebProj.Tests/WebProj.Tests.csproj.
接著搭配 -p:CollectCoverage=true
參數去執行 dotnet test
。
$ dotnet test -p:CollectCoverage=true
Test run for /Users/ironman/dotnet-sln/WebProj.Tests/bin/Debug/netcoreapp2.2/WebProj.Tests.dll(.NETCoreApp,Version=v2.2)
Microsoft (R) Test Execution Command Line Tool Version 16.2.0-preview-20190606-02
Copyright (c) Microsoft Corporation. All rights reserved.
Starting test execution, please wait...
Test Run Successful.
Total tests: 1
Passed: 1
Total time: 1.3340 Seconds
Calculating coverage result...
Generating report '/Users/ironman/dotnet-sln/WebProj.Tests/coverage.json'
+---------------+------+--------+--------+
| Module | Line | Branch | Method |
+---------------+------+--------+--------+
| WebProj.Views | 0% | 0% | 0% |
+---------------+------+--------+--------+
| WebProj | 0% | 0% | 0% |
+---------------+------+--------+--------+
+---------+------+--------+--------+
| | Line | Branch | Method |
+---------+------+--------+--------+
| Total | 0% | 0% | 0% |
+---------+------+--------+--------+
| Average | 0% | 0% | 0% |
+---------+------+--------+--------+
Tada!Line Coverage、Branch Coverage、Method Coverage 的數據就出現在命令列介面中啦!但是我目前這個專案沒有寫任何單元測試,所以都還是 0%。