C# 9/10 顶级语句和 ExcludeFromCodeCoverage-Attribute?

C# 9/10 top-level statements and ExcludeFromCodeCoverage-Attribute?

我通常将属性 [ExcludeFromCodeCoverage] 设置到我的程序 class,因为无论如何都不可能对此 class 进行单元测试(或者也没有意义),所以它在覆盖率报告中没有显示为“缺失”:

[ExcludeFromCodeCoverage]
public static class Program
{
    public static void Main(string[] args)
    {
       // do something awesome
    }
}

但是 top-level statements I don't know how to handle this. It seems not to be possible to set attributes, as I found here:

到目前为止,我坚持 classic Class 减法,但也许他们在考虑单元测试代码覆盖率时考虑了其他问题?

自 C# 10 起,top-level 语句生成已更改,现在您可以将 partial Program class 添加到 top-level 语句的末尾并向其添加属性:

[ExcludeFromCodeCoverage]
public partial class Program { }

请注意,在初始功能规范中(对于 C# 9)states that the actual names used by compiler are implementation dependent but since C# 10 and NET 6 using partial class is one of the recommended approaches for unit testing ASP.NET 使用 top-level 语句的核心应用程序。

但我个人会说,如果您需要这样的“高级”方案,您应该切换回“普通老式”方案 Program classes.