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

5.9k Views Asked by At

I usually set the attribute [ExcludeFromCodeCoverage] to my Program class, as there are no unit tests for this class possible anyways (or don't make sense either), so it doesn't show up as "missing" in the coverage report:

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

But with top-level statements I don't know how to handle this. It seems not to be possible to set attributes, as I found here: https://stackoverflow.com/a/69962982/1099519

So far, I stick to the classic Class declaration, but maybe they thought about something else, when it comes to unit test code coverage?

2

There are 2 best solutions below

7
On BEST ANSWER

Since C# 10 the top-level statement generation was changed and now you can add partial Program class to the end of top-level statement (or in separate file) and add attribute to it:

[ExcludeFromCodeCoverage]
public partial class Program { }

Note that in initial feature specification (for 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 Core apps which use top-level statements.

But personally I would say that if you need such "advanced" scenarios you should switch back to the "plain old" Program classes.

0
On

This is what worked for me (.NET 7):

[ExcludeFromCodeCoverage]
public static partial class Program { }

Looks like the generated Program class is static, so putting [ExcludeFromCodeCoverage] on non-static partial Program class doesn't apply to top-level code. Not sure why that is, can't find documentation stating that generated Program is static.