12

To exclude my code from code coverage in a .net core webapi project, I apply the [System.Diagnostics.Analysis.ExcludeFromCodeCoverage] attribute to the unwanted classes.

Now I would like to exclude Program.cs from my code coverage. However, in .net 6 I don't know how to apply an attribute to this file because it does not have a class declaration. Can anyone guide me on how I can apply an attribute to this file?

Wayne Allen
  • 1,605
  • 1
  • 10
  • 16
  • 1
    _"because it does not have a class declaration."_ - say again? – ProgrammingLlama Dec 23 '21 at 01:31
  • 1
    C# 10 top-level statements. – Scott Hannen Dec 23 '21 at 01:37
  • 1
    It did. Thanks gunr2171 – Wayne Allen Dec 23 '21 at 02:20
  • 1
    Add program and public static Main to it. Then add the attribute. – Calvin Mar 08 '22 at 16:01
  • 1
    If it is all to do with `ExcludeFromCodeCoverage`, just add a `CodeCoverage.runsettings` file. For local in test options auto detect this file and add `.*\\Program.*`. This will exclude Program. cs from your local code coverage, pipeline and sonarcloud coverage as well. See [document](https://learn.microsoft.com/en-us/visualstudio/test/configure-unit-tests-by-using-a-dot-runsettings-file?view=vs-2022) – Laurent Greyling Aug 08 '22 at 09:08
  • 2
    This is definitely not a duplicate of that other question which is asking about static variables. – Develorem Aug 22 '22 at 01:34
  • Hi Wayne, were you able to find a solution for this? If yes, can you pls post it here? – Vivek Gopalakrishnan Sep 07 '22 at 14:07
  • This is not a duplicate. The proposed duplicate does not cover the scope of this question. There is an answer that could cover this question, but it is not the only way to do it. The comment above from Laurent and the answer from Anuraj better answer this question. – CristisS Mar 21 '23 at 16:21

1 Answers1

6

I don't think you can use attributes, but you can exclude the program.cs in the dotnet test command - like this.

dotnet test /p:CollectCoverage=true /p:CoverletOutputFormat=cobertura /p:ExcludeByFile="**/program.cs"

Anuraj
  • 18,859
  • 7
  • 53
  • 79