Search code examples
c#unit-testingmoqcode-coveragecoverlet

C# - Exclude lambda expression from code coverage


I have a particular third party class that has an event handler. I have setup MyEventHandler method which I am able to test using reflection, so I know that is well tested. However I am getting a missing line coverage where I setup the handler (since that part is never being called). How can I Exclude that from code coverage somehow? MyClass object is a sealed class so I can not mock it and invoke the handler via test.

MyClass myObj = new(); // sealed class, so can't mock using moq

myObj.OnEvent += () => 
    {
        MyEventHandler(); // This line is uncovered
    }

Things I have tried.

  1. Making entire handler as a method, however again the actual lambda expression is still shown uncovered.
  2. Marked the above method of setup with ExcludeFromCodeCoverage
  3. I have also tried using runsettings file, which works however due to the GeneratedCodeAttribute/CompilerGeneratedAttribute exclusion, it also excludes my async functions, which is not desired.

How do I exclude the lambda expression from code coverage?


Solution

  • Okay so got this resolved. I am still posting here in case if it helps others in future. I have marked the event with [ExcludeFromCodeCoverage] and that seems to exclude the event which in this case is what I wanted.

    MyClass myObj = new();
    
    myObj.OnEvent += [ExcludeFromCodeCoverage] () => 
        {
            MyEventHandler();
        }