ExpectedException Attribute Usage

青春壹個敷衍的年華 提交于 2020-01-12 03:06:48

问题


I am trying to work with the ExpectedException attribute in a C# UnitTest, but I am having issues getting it to work with my particular Exception. Here's what I got:

NOTE: I wrapped asterisks around the line that is giving me the trouble.

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

I have the ExpectedException catching the base type Exception. Shouldn't this take care of it? I have tried using AttributeUsage, but it wasn't helping either. I know I can wrap it in a try/catch block, but I'd like to see if I can figure this style out.

Thanks all!


回答1:


It will fail unless the type of exception is exactly the type you've specified in the attribute 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;
    }

However this will pass ...

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


来源:https://stackoverflow.com/questions/19108107/expectedexception-attribute-usage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!