When the project in which I was working was going through performance analysis, we found our project has a lot of warning generated by code analysis and also code coverage is not up to the mark. We analyze warnings and methods that were not under test coverage. What we found was that we were mostly following best practices but still code analysis left us with a lot of warnings. The same goes with code-coverage, all new methods were having proper test cases for all scenarios. What was going wrong???
The actual problem was:
So what can the solution be?
The solution was nevertheless easier then we thought. Microsoft has provision for disabling code-analysis warnings and excluding code-coverage for such a scenarios only in System.Diagnostics.CodeAnalysis namespace.
System.Diagnostics.CodeAnalysis
The System.Diagnostics.CodeAnalysis namespace contains classes for interaction with code analysis tools:
ExcludeFromCodeCoverageAttribute
Actual working example:
[System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] public static OperationControl GetInstance() { //Your code goes here }
In the above code, ExcludeFromCodeCoverage attribute will prevent the method from being covered in test coverage and thus increase code coverage percentage. Please note only third-party tested code, test methods and such cases are recommended for using the attribute and it must not be applied to all/most of methods that will defeat the purpose of code-coverage check.
ExcludeFromCodeCoverage
SuppressMessageAttribute
The SuppressMessage attribute has the following format:
SuppressMessage
[Scope:SuppressMessage("Rule Category", "Rule Id", Justification = "Justification", MessageId = "MessageId", Scope = "Scope", Target = "Target")]
Where:
CAXXXX
CAXXXX:FriendlyTypeName
[System.Diagnostics.CodeAnalysis.SuppressMessage ("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] public static OperationControl GetInstance() { //Your code goes here }
In the above code, SuppressMessage attribute will prevent Microsoft.Design warning”CA1024?.
For more detailed information, you can refer to the following links on MSDN:
CodeProject