预期异常属性用法

本文关键字:用法 属性 异常 | 更新日期: 2023-09-27 18:33:20

我正在尝试在C# UnitTest中使用ExpectedException属性,但是在使其与我的特定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 块中,但我想看看我是否能弄清楚这种风格。

谢谢大家!

预期异常属性用法

除非异常类型与您在属性中指定的类型完全一致,否则它将失败例如

通过:-

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

失败:-

    [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;
    }