2012-06-25 96 views
6

有沒有辦法將自動生成的類標記爲ExcludeFromCodeCoverage。我在其他領域使用該屬性並且效果很好。但是,如果您打開自動生成的代碼並將這些類標記爲ExcludeFromCodeCoverage,那麼一旦您重新生成該類,它就會被覆蓋。ExcludeFromCodeCoverage排除自動生成的代碼

我可以在dbml後面的代碼中創建部分類,並將其應用於該屬性,並且它可以工作,但是,這將會產生大量的部分類。

+0

你可以讓自動生成的類帶有「partial」(比如,以某種方式改變生成器)嗎? –

回答

4

您可以使用PostSharp或其他AOP框架創建方面將適用ExcludeFromCodeCoverageAttribute指定類型或命名空間:

[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)}; 
    } 
} 

然後,只需將此方面的組裝和提供要排除的命名空間。在編譯過程中PostSharp將在My.AutogeneratedCode命名空間添加ExcludeFromCodeCoverageAttribute的所有類:

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

示例代碼和解釋,你可以找到here