1. 程式人生 > 其它 >通過使用runsetting檔案配置單元測試程式碼覆蓋率

通過使用runsetting檔案配置單元測試程式碼覆蓋率

(適用於DOTNET)

在專案中,我們的CI 分成三類:PR CI, Fast CI和QA CI。 其中QA CI中我們不僅要使用Sonar Qube來檢查程式碼規範,還執行單元測試並檢視程式碼覆蓋率。但是因為專案中引用了一些其他的類庫, 這樣在統計程式碼覆蓋率的時候,也會一併算入進來。對統計結果造成了影響。

因此,我們需要指定程式碼覆蓋率的檢查範圍。使用runsettings檔案就是一個不錯的方法。

我們先看看幫助說明

> dotnet test --help

 

Options:

  -h, --help                               Show command line help.

  
-s, --settings <SETTINGS_FILE> The settings file to use when running tests. -t, --list-tests List the discovered tests instead of running the tests. ……

其中 -s 開關就是指定runsettings檔案的

關於runsettings檔案的介紹, 可以參考《使用 .runsettings 檔案配置單元測試》。

本專案中使用的runsettings檔案內容如下

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <RunSettings>
 3   <!-- Configurations that affect the Test Framework -->
 4   <RunConfiguration>
 5     <MaxCpuCount>4</MaxCpuCount>
 6     <BatchSize>4</BatchSize>
 7     <TestCaseFilter>TestCategory=passed</
TestCaseFilter> 8 </RunConfiguration> 9 <DataCollectionRunSettings> 10 <DataCollectors> 11 <DataCollector friendlyName="Code Coverage" uri="datacollector://Microsoft/CodeCoverage/2.0" assemblyQualifiedName="Microsoft.VisualStudio.Coverage.DynamicCoverageDataCollector, Microsoft.VisualStudio.TraceCollector, Version=11.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"> 12 <Configuration> 13 <CodeCoverage> 14 <ModulePaths> 15 <Include> 16 <ModulePath>.*myproj\..*\.dll$</ModulePath> 17 <ModulePath>.*\.exe$</ModulePath> 18 </Include> 19 <Exclude> 20 <ModulePath>.*myproj\.common.*\.dll$</ModulePath> 21 <ModulePath>.*myproj\.data.*\.dll$</ModulePath> 22 </Exclude> 23 </ModulePaths> 24 <CollectAspDotNet>False</CollectAspDotNet> 25 </CodeCoverage> 26 </Configuration> 27 </DataCollector> 28 </DataCollectors> 29 </DataCollectionRunSettings> 30 </RunSettings>

其中 include節點中是指要包括的檔案, exclude中是指不包括的檔案,應該很好理解。需要注意的是點號需要轉義成“\.” , 星號需要轉義成".*"

然後就可以使用命令執行單元測試,並收集程式碼覆蓋率了。

dotnet test $(TestProjectPath)  -s $(RunSettings) --filter "TestCategory=passed"

程式碼覆蓋率的結果會被管道自動收集,並且在結果頁上提供下載。