You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Coverlet未遵守.runsettings中MoveNext()函数排除规则如何解决?

解决方案:直接用Coverlet排除异步自动生成的MoveNext方法

你的问题核心在于:你使用的XPlat Code Coverage基于Coverlet实现,而非Visual Studio内置的代码覆盖率收集器,因此原本针对VS收集器的.runsettings配置不会生效。以下是几种直接通过Coverlet实现排除的简洁方法:

方法1:命令行参数直接排除

在dotnet test命令中添加--exclude参数,直接指定要排除的方法或类:

排除所有MoveNext方法

dotnet test --collect:"XPlat Code Coverage" --results-directory .coverage --exclude "[*]*.MoveNext"

更精确:排除所有异步状态机生成的类(推荐)

异步方法编译后会生成类似<CreateMessages>d__10的嵌套状态机类,直接排除这类类能彻底避免所有自动生成的代码被统计:

dotnet test --collect:"XPlat Code Coverage" --results-directory .coverage --exclude "[*]*+<*>*"
  • [*]:匹配所有程序集
  • *+<*>*:匹配所有包含<的嵌套类(异步状态机的命名特征)

方法2:使用Coverlet专属的.runsettings文件

创建coverlet.runsettings文件(注意和你原来的VS版本配置区分),配置排除规则:

<?xml version="1.0" encoding="utf-8"?>
<RunSettings>
  <DataCollectionRunSettings>
    <DataCollectors>
      <DataCollector friendlyName="XPlat Code Coverage">
        <Configuration>
          <Exclude>[*]*.MoveNext;[*]*+<*>*</Exclude>
        </Configuration>
      </DataCollector>
    </DataCollectors>
  </DataCollectionRunSettings>
</RunSettings>

然后用以下命令运行测试:

dotnet test --collect:"XPlat Code Coverage" --results-directory .coverage --settings coverlet.runsettings

方法3:在测试项目文件中配置

直接在测试项目的.csproj里添加全局排除规则,无需每次命令行传参:

<PropertyGroup>
  <ExcludeFromCodeCoverage>[*]*.MoveNext;[*]*+<*>*</ExcludeFromCodeCoverage>
</PropertyGroup>

之后直接运行测试命令即可:

dotnet test --collect:"XPlat Code Coverage" --results-directory .coverage

验证效果

执行上述任意方法后,再用你的合并命令:

dotnet-coverage merge .coverage\*.xml --remove-input-files --recursive -f xml -o coverage.xml

生成的coverage.xml中将不再包含自动生成的MoveNext()方法,SonarQube扫描也不会再出现行号越界的错误。


内容的提问来源于stack exchange,提问作者ilitirit

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 04:18:23