2013-10-01 33 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

难道我们不需要围绕预期的违规代码尝试捕获预期的异常吗? –