--- tags: unit test, CI, CD --- # 自動執行單元測試 這是一個上傳到 Gitlab後即可自動執行單元測試,並統計涵蓋率的 script的說明文件。 ## 事前準備 從 nuget安裝以下 package: * coverlet.collector (收集 test coverage,僅限 .NetCore專案使用) * coverlet.msbuild (令 dotnet test 時可更改輸出的 xml位置,不一定要安裝) * JunitXml.TestLogger (輸出 JUnit格式 test report,gitlab test report唯一接受的格式) Builder Server需要安裝 reportgenerator,用來輸出 unit test report: `dotnet tool install -g dotnet-reportgenerator-globaltool` # 在專案新增以下檔案 ## .gitlab-ci.yml ```yaml= stages: - test test: stage: test tags: # 指令 runner的名字 - windows - netframework script: - .\unittest.ps1 "TestProjectName" artifacts: # 上傳 test report 到 gitlab reports: # 如果有上傳 cobertura的話,會在 pipeline -> test 看到個別的 test結果 coverage_report: coverage_format: cobertura path: "coverage.cobertura.xml" junit: "test_results.xml" expire_in: 1 month paths: - report/* # 使用 regular expression parse整個 console output # 如果 test 的工具不會自動輸出,就要自己讀檔然後輸出成可以 parser的格式 coverage : '/Code coverage rate : \d+.\d+/' ``` ## unittest.ps1 ```shell= param($path) # dotnet restore : 還原所有依賴的 package # dotnet test : 重建專案以及執行單元測試 # 因 dotnet test沒有辦法指定 nuget.config,所以將指令拆成兩段 dotnet restore --configfile nuget.config dotnet test --collect:"XPlat Code Coverage" --logger:"junit;LogFileName=test_results.xml;MethodFormat=Class;FailureBodyFormat=Verbose" --no-restore if (!$?) { throw [System.Exception]"Unit test fail" } # 找到 unit test result的資料夾(資料夾名字是 guid,所以要動態搜尋) $testResultFolder = (Get-ChildItem -Directory "$path\TestResults\" | Sort-Object -Descending)[0].Name if (!$?) { throw [System.Exception]"Cannot found TestResult" } # 產生報表 reportgenerator -reports:"$path\TestResults\$testResultFolder\coverage.cobertura.xml" -targetdir:"report" -reporttypes:Html # 將報表以及測試結果搬到外層,上傳到 gitlab的時候會比較方便 cp "$path\TestResults\$testResultFolder\coverage.cobertura.xml" "coverage.cobertura.xml" cp "$path\TestResults\test_results.xml" "test_results.xml" # 從 cobertura.xml的 tag "coverage"讀取屬性 "line-rate"的值 [XML]$coverage = Get-Content "coverage.cobertura.xml" # 因 gitlab需要涵蓋率的百分比,所以將 string轉換為 double並乘以 100 $rate = ($coverage.coverage.'line-rate' -as [double]) * 100 # 輸出到 console令 gitlab可以讀取涵蓋率 write-host "Code coverage rate : $rate" ``` 若 Ci Pipeline執行成功,可以在底下看到涵蓋率跟 artifacts 
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up