Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ExcludeFromCodeCoverage Exclude Auto-Generated Code

Is there a way to mark an auto-generated class as ExcludeFromCodeCoverage. I am using that attribute in other areas and works great. But if you open the code of the auto-generated guy and mark the classes as ExcludeFromCodeCoverage, once you re-generate that class itll be over written.

I can create partial classes in the code behind of the dbml and apply that attribute to it and it works, however, that would make for a lot of partial classes.

like image 618
Adam Avatar asked Jun 25 '12 18:06

Adam


People also ask

How do you exclude code from code coverage?

To exclude test code from the code coverage results and only include application code, add the ExcludeFromCodeCoverageAttribute attribute to your test class.

How do I enable analyze code coverage in Visual Studio 2019?

On the Test menu, select Analyze Code Coverage for All Tests. You can also run code coverage from the Test Explorer tool window. Show Code Coverage Coloring in the Code Coverage Results window. By default, code that is covered by tests is highlighted in light blue.


1 Answers

You can use PostSharp or other AOP framework to create aspect which will apply ExcludeFromCodeCoverageAttribute to specified types or namespaces:

[Serializable]
[AttributeUsage(AttributeTargets.Assembly)]
[MulticastAttributeUsage(MulticastTargets.Class | MulticastTargets.Struct)]
[ProvideAspectRole(StandardRoles.PerformanceInstrumentation)]
public sealed class DisableCoverageAttribute : TypeLevelAspect, IAspectProvider
{
    public IEnumerable<AspectInstance> ProvideAspects(object targetElement)
    {
        Type disabledType = (Type)targetElement;

        var introducedExclusion = new CustomAttributeIntroductionAspect(
              new ObjectConstruction(typeof (ExcludeFromCodeCoverageAttribute)));

        return new[] {new AspectInstance(disabledType, introducedExclusion)};
    }
}

Then just apply this aspect to assembly and provide namespace which you want to exclude. During compilation PostSharp will add ExcludeFromCodeCoverageAttribute to all classes in My.AutogeneratedCode namespace:

[assembly: DisableCoverage(AttributeTargetTypes="My.AutogeneratedCode.*")]

Sample code and explanations you can find here.

like image 199
Sergey Berezovskiy Avatar answered Sep 20 '22 06:09

Sergey Berezovskiy