Подтвердить что ты не робот

Использование атрибута ExpectedException

Я пытаюсь работать с атрибутом 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, но я хотел бы посмотреть, могу ли я понять этот стиль.

Спасибо всем!

4b9b3361

Ответ 1

Он будет терпеть неудачу, если тип исключения не будет таким же типом, который вы указали в атрибуте например

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