How do I write a unit test that should fail?

463 Views Asked by At

If I make a test that should throw a fatal error, how can I handle that? For instance, how can I write this test to ensure a variable is deleted properly:

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

There are 1 best solutions below

0
On BEST ANSWER

You can parameterize the Test attribute as Test(ShouldFail=true).

The test process first runs all tests that shouldn't fail, then runs all tests that should. If any tests that should fail don't, the remaining should-fail tests are still run.

For instance, testing this 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()
    {

    }

}

...will first successfully complete TestScopeShouldNotFail, then will unexpectedly complete TestScopeShouldFailButSucceeds, then will expectedly fail in TestScopeShouldFail. Thus, it will produce one failed test for TestScopeShouldFailButSucceeds.