如何编写应该失败的单元测试?

How do I write a unit test that should fail?

如果我进行的测试应该抛出致命错误,我该如何处理?例如,我如何编写此测试以确保正确删除变量:

[Test]
public static void TestScope()
{
    String str;
    {
        str = scope .();
    }
    str.ToUpper(); // str should be marked as deleted here
}

您可以将 Test 属性参数化为 Test(ShouldFail=true)

测试过程首先 运行 所有不应失败的测试,然后 运行 所有应该失败的测试。如果任何应该失败的测试没有失败,其余应该失败的测试仍然是 运行。

例如,测试这个 class:

class Program
{
    [Test(ShouldFail=true)]
    public static void TestScopeShouldFailButSucceeds()
    {
        String str;
        {
        str = scope:: .();
        }

        str.ToUpper(); // will not fail
    }

    [Test(ShouldFail=true)]
    public static void TestScopeShouldFail()
    {
        String str;
        {
        str = scope .();
        }

        str.ToUpper(); // will fail
    }

    [Test]
    public static void TestScopeShouldNotFail()
    {
        String str;
        {
        str = scope:: .();
        }

        str.ToUpper(); // will not fail
    }

    public static void Main()
    {

    }

}

...将首先成功完成 TestScopeShouldNotFail,然后意外完成 TestScopeShouldFailButSucceeds,然后预计会在 TestScopeShouldFail 中失败。因此,它将为 TestScopeShouldFailButSucceeds.

生成一个失败的测试