使用 lambda 表达式的测试方法的静态分析 CA1811 错误

Static analysis CA1811 error on Test methods with lambda expressions

我在编写测试时发现了一个奇怪的 Visual Studio 静态分析错误。下面的代码在两种测试方法 FailCAPassCA.

上生成 CA1811

'ClassToTestTests.FailCA()' appears to have no upstream public or protected callers. 'ClassToTestTests.PassCA()' appears to have no upstream public or protected callers.

代码:

using System;
using NUnit.Framework;
using static Namespace.ClassToTest;
using static NUnit.Framework.Assert;

namespace Namespace {
    public static class ClassToTest {
        public static object MethodToTest (object value) => value;
        }

    [TestFixture]
    internal sealed class ClassToTestTests {
        private object value = new object ();

        [Test]
        public static void FailCA () => Throws<ArgumentNullException> (() => MethodToTest (null));

        [Test]
        public void PassCA () => Throws<ArgumentNullException> (() => MethodToTest (value));
        }
    }

如果我评论 FailCA 或将其代码更改为这样的内容

[Test]
public void FailCA () {
    value = null;
    Throws<ArgumentNullException> (() => MethodToTest (value));
}

然后两种方法的警告都消失了。所以看起来 () => MethodToTest (null) 与此有关。

知道为什么所有方法都会生成警告吗?

我在启用所有规则的情况下设置了代码分析。也许您已抑制 CA1812,因为它会出现在大多数 NUnit 测试装置上,因为它们由框架动态调用。无论哪种方式:

使用您的代码,我收到了您在问题中列出的 2 条警告。当我注释掉 FailCA 或使其成为非静态时,我不会收到这些警告。但是我确实收到了另一个警告:

Warning CA1812 'ClassToTestTests' is an internal class that is apparently never instantiated. If so, remove the code from the assembly. If this class is intended to contain only static methods, consider adding a private constructor to prevent the compiler from generating a default constructor.

所以,你原来的警告消失的原因是因为代码分析器已经确定整个 class 从未被实例化并且没有静态方法所以它不需要费心去检查 class 中的每个方法是否=19=] 已被调用。

当您取消注释 FailCA 时,存在静态方法的事实意味着它需要检查调用者的方法,即使它知道 class 从未被实例化。