(适用于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"

 

代码覆盖率的结果会被管道自动收集,并且在结果页上提供下载。

 

 

posted on 2021-06-29 15:43  Weizheng  阅读(381)  评论(5编辑  收藏  举报