我在编写测试时发现了一个奇怪的 Visual Studio 静态分析错误。下面的代码生成 CA1811两种测试方法 FailCA
和 PassCA
。
'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.
所以,你原来的警告消失的原因是因为代码分析器已经确定整个类从未被实例化并且没有静态方法,所以它不需要费心去检查类中的每个方法是否都被调用了。
当您取消注释 FailCA 时,存在静态方法的事实意味着它需要检查调用方的方法,即使它知道该类从未被实例化。
关于c# - 使用 lambda 表达式的测试方法的静态分析 CA1811 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37539758/