通过


MSTEST0063:测试类应具有有效的构造函数

资产 价值
规则 ID MSTEST0063
标题 测试类应具有有效的构造函数
类别 Usage
修复是中断修复还是非中断修复 Non-breaking
默认启用 是的
默认严重性 警告
是在版本 中引入的 4.1.0
有修复代码的办法吗

原因

测试类没有有效的构造函数。 有效的构造函数是 public 无参数的,或者具有类型为 TestContext单个参数。

规则说明

测试类必须具有无参数或接受单个 TestContext 参数的公共构造函数。 这样,测试框架就可以正确实例化测试类。

非公共构造函数、具有不受支持的类型的参数或具有多个参数无效,并阻止测试框架创建测试类的实例。

[TestClass]
public class MyTestClass
{
    private MyTestClass() // Violation - constructor is not public
    {
    }
}
[TestClass]
public class MyTestClass
{
    public MyTestClass(string value) // Violation - parameter type is not supported
    {
    }
}
[TestClass]
public class MyTestClass
{
    public MyTestClass(TestContext testContext, int value) // Violation - multiple parameters
    {
    }
}

如何修复违规行为

确保测试类具有有效的构造函数。 有效的构造函数必须满足以下条件:

  1. 声明为 public.
  2. 无参数或接受单个 TestContext 参数。

无参数构造函数

[TestClass]
public class MyTestClass
{
    public MyTestClass()
    {
    }

    [TestMethod]
    public void TestMethod()
    {
    }
}

使用 TestContext 的构造函数

[TestClass]
public class MyTestClass
{
    private readonly TestContext _testContext;

    public MyTestClass(TestContext testContext)
    {
        _testContext = testContext;
    }

    [TestMethod]
    public void TestMethod()
    {
        _testContext.WriteLine("Test is running...");
    }
}

隐式无参数构造函数

如果未定义任何构造函数,编译器会自动生成公共无参数构造函数:

[TestClass]
public class MyTestClass
{
    [TestMethod]
    public void TestMethod()
    {
    }
}

有效和无效的构造函数

如果测试类具有多个构造函数,则至少一个构造函数必须有效:

[TestClass]
public class MyTestClass
{
    public MyTestClass() // Valid - this makes the class valid
    {
    }

    private MyTestClass(int x) // Invalid, but ignored because a valid constructor exists
    {
    }

    [TestMethod]
    public void TestMethod()
    {
    }
}

何时禁止显示警告

不要禁止显示此规则的警告。 测试框架无法实例化没有有效构造函数的测试类,并且不会运行测试。

禁止显示警告

如果只想抑制单个冲突,请将预处理器指令添加到源文件以禁用该规则,然后重新启用该规则。

#pragma warning disable MSTEST0063
// The code that's violating the rule is on this line.
#pragma warning restore MSTEST0063

若要禁用文件、文件夹或项目的规则,请在none中将其严重性设置为

[*.{cs,vb}]
dotnet_diagnostic.MSTEST0063.severity = none

有关详细信息,请参阅 如何禁止显示代码分析警告