Tôi đang cố gắng làm việc với thuộc tính ExpectedException
trong một C# UnitTest
, nhưng tôi đang gặp sự cố để làm việc với Exception
cụ thể của tôi. Dưới đây là những gì tôi nhận được:Cách sử dụng thuộc tính ExpectedException
LƯU Ý: Tôi đã bao bọc dấu hoa thị quanh đường khiến tôi gặp rắc rối.
[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);
}
}
Tôi có ExpectedException
bắt loại cơ sở Exception
. Điều này có nên chăm sóc nó không? Tôi đã thử sử dụng AttributeUsage
, nhưng cũng không giúp được gì. Tôi biết tôi có thể quấn nó trong một khối try/catch, nhưng tôi muốn xem liệu tôi có thể hình dung ra phong cách này không.
Cảm ơn tất cả!
Làm việc như một sự quyến rũ, cảm ơn lời giải thích. Đây là một số đại diện dễ dàng, cổ vũ! – Jonathan
tôi sẽ không khuyến khích [TestMethod()] [ExpectedException (typeof (System.Exception), AllowDerivedTypes = true)] Đối với cùng một lý do tôi sẽ không khuyến khích ... catch (Exception ex) {.... – Mick
Chúng ta không cần thử/nắm bắt xung quanh mã vi phạm dự kiến để bắt được ngoại lệ dự kiến? –