2013-10-01 34 views
18

我正在嘗試使用C# UnitTest中的ExpectedException屬性,但我遇到了問題,無法使用我的特定Exception。這是我得到的:ExpectedException屬性用法

注意:我纏着星號繞着那條給我麻煩的線。

[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塊中,但是我想看看我能否把這個風格弄清楚。

謝謝大家!

回答

36

它會失敗,除非異常的類型正是您在屬性 如

PASS指定的類型: -

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

工程就像一個魅力,感謝您的解釋。這是一些簡單的代表,歡呼! – Jonathan

+5

我不會鼓勵 [TestMethod的()] [的ExpectedException(typeof運算(System.Exception的),AllowDerivedTypes =真)] 出於同樣的原因,我不鼓勵 ... 趕上(異常前) {... – Mick

+0

難道我們不需要圍繞預期的違規代碼嘗試捕獲預期的異常嗎? –