Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable specific Code Analysis Warning for entire class

I'm trying to disable a code analysis rule across an entire class, but NOT for the entire project, just a single class. In the example below, the build generates a CA1822 warning because it thinks that the unit test methods should be static.

The fix is to add the following attribute to each unit test method: [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")]

However, that's cumbersome and clutters a class with many unit tests.

I've tried:

  1. Moving the attribute to the class
  2. Wrapping all of the methods in

#pragma warning disable CA1822

#pragma warning restore CA1822

Neither of these two approaches have worked.

public class TestClass
{
    public TestClass()
    {
        // some setup here
    }

    [Fact]
    public void My_Unit_Test1()
    {
        // the 'this' parameter is never used, causes CA warning 1822
    }

    [Fact]
    public void My_Unit_Test2()
    {
        // the 'this' parameter is never used, causes CA warning 1822
    }
}

Using VS2015 Update 2, .net 4.61, and the new Code Analysis Analyzers.

like image 468
SFun28 Avatar asked Jul 07 '16 13:07

SFun28


People also ask

How do I turn off Roslyn Code Analysis?

Disable below setting in Tools/Options/Text Editor/C#/Advanced and disable use 64-bit process for code analysis under analysis group.

How do I disable FxCop?

csproj files (I slapped it in the first <PropertyGroup> I could find) and stop using Analyze > Run Code Analysis because that still runs the old FxCop. If you use the old ASP.NET (not Core), right click on a project and click Unload project before you can edit the . csproj.

What is pragma warning in C#?

C# provides a feature known as the #pragma feature to remove the warnings. Sometimes we declare a variable but do not use the variable anywhere in the entire program so when we debug our code the compiler gives a warning so using the #pragma we can disable these types of warnings.


1 Answers

Click the light bulb icon [💡] or press Ctrl + . combination. This should open a context menu like bellow.

suppression

Then select Suppress or Configure issues > Suppress XXX > in Suppression File menu item. It will create GlobalSuppression.cs file if not exists and add a new line to it.

By default it will only suppress warning for selected member (method). You can change Scope to type and Target to full class name (eg: Project.Domain.MyAwesomeClass).

Here's an example:

[assembly: SuppressMessage("Design", "CA1062:Validate arguments of public methods", Justification = "This parameter of extension methods are always not null.", Scope = "type", Target = "Fonibo.Identity.Extensions.ClaimsIdentityExtension")]
like image 123
TheMisir Avatar answered Sep 29 '22 20:09

TheMisir