2013-10-01 11 views
18

Próbuję pracować z atrybutem ExpectedException w C# UnitTest, ale mam problemy z uzyskaniem go do pracy z moim konkretnym Exception. Oto, co otrzymałem:ExpectedException Attribute Usage

UWAGA: Owinąłem gwiazdki wokół linii, która sprawia mi kłopot.

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

mam ExpectedException łapanie typ bazowy Exception. Czy to nie powinno zająć się tym? Próbowałem używać AttributeUsage, ale to też nie pomagało. Wiem, że mogę go zawrzeć w bloku try/catch, ale chciałbym zobaczyć, czy mogę wymyślić ten styl.

Dzięki!

Odpowiedz

36

nie powiedzie, chyba że rodzaj wyjątku jest dokładnie typ już określony w atrybucie np

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

jednak to minie ...

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

Działa jak czar, dzięki za wyjaśnienie. Oto kilka łatwych powtórzeń, okrzyki! – Jonathan

+5

Nie chciałbym zachęcić [TestMethod()] [ExpectedException (typeof (System.Exception) AllowDerivedTypes = true)] Z tego samego powodu nie będę zachęcać ... catch (Exception ex) {... – Mick

+0

Czy nie potrzebujemy próbować/złapać wokół oczekiwanego kodu przestępczego, aby złapać oczekiwany wyjątek? –

Powiązane problemy