ExpectedException属性用法

时间:2013-10-01 04:39:56

标签: c# unit-testing exception expected-exception

我正在尝试使用ExpectedException中的C# UnitTest属性,但我遇到了与我的特定Exception一起使用的问题。这就是我得到的:

注意:我在行周边包裹着星号,这给我带来了麻烦。

    [ExpectedException(typeof(Exception))]
    public void TestSetCellContentsTwo()
    {
        // Create a new Spreadsheet instance for this test:
        SpreadSheet = new Spreadsheet();

        // If name is null then an InvalidNameException should be thrown. Assert that the correct 
        // exception was thrown.
        ReturnVal = SpreadSheet.SetCellContents(null, "String Text");
        **Assert.IsTrue(ReturnVal is InvalidNameException);**

        // If text is null then an ArgumentNullException should be thrown. Assert that the correct
        // exception was thrown.
        ReturnVal = SpreadSheet.SetCellContents("A1", (String) null);
        Assert.IsTrue(ReturnVal is ArgumentNullException);

        // If name is invalid then an InvalidNameException should be thrown. Assert that the correct 
        // exception was thrown.
        {
            ReturnVal = SpreadSheet.SetCellContents("25", "String Text");
            Assert.IsTrue(ReturnVal is InvalidNameException);

            ReturnVal = SpreadSheet.SetCellContents("2x", "String Text");
            Assert.IsTrue(ReturnVal is InvalidNameException);

            ReturnVal = SpreadSheet.SetCellContents("&", "String Text");
            Assert.IsTrue(ReturnVal is InvalidNameException);
        }
    }

我有ExpectedException捕获基本类型Exception。这不应该照顾它吗?我曾尝试使用AttributeUsage,但它也没有帮助。我知道我可以将它包装在try / catch块中,但是我想知道我是否能想出这种风格。

全部谢谢!

1 个答案:

答案 0 :(得分:42)

除非异常类型与您在属性中指定的类型完全相同,否则它将失败 e.g

PASS: -

    [TestMethod()]
    [ExpectedException(typeof(System.DivideByZeroException))]
    public void DivideTest()
    {
        int numerator = 4;
        int denominator = 0;
        int actual = numerator / denominator;
    }

FAIL: -

    [TestMethod()]
    [ExpectedException(typeof(System.Exception))]
    public void DivideTest()
    {
        int numerator = 4;
        int denominator = 0;
        int actual = numerator / denominator;
    }

然而,这将通过......

    [TestMethod()]
    [ExpectedException(typeof(System.Exception), AllowDerivedTypes=true)]
    public void DivideTest()
    {
        int numerator = 4;
        int denominator = 0;
        int actual = numerator / denominator;
    }