我不想使用[ExpectedException(ExceptionType = typeof(Exception),ExpectedMessage =「」)],而是想在我的方法中包含異常。我可以這樣做嗎?請任何例子。如何包含內部方法
謝謝
我不想使用[ExpectedException(ExceptionType = typeof(Exception),ExpectedMessage =「」)],而是想在我的方法中包含異常。我可以這樣做嗎?請任何例子。如何包含內部方法
謝謝
是這樣的:
[TestMethod]
public void FooTest()
{
try
{
// run test
Assert.Fail("Expected exception had not been thrown");
}
catch(Exception ex)
{
// assert exception or just leave blank
}
}
你的問題不太合理。作爲一種預感,我猜你在問單元測試中是否會遇到異常,然後即使異常已被提出,也可以執行斷言?
[TestMethod]
public void Test1()
{
try{
// You're code to test.
}
catch(Exception ex){
Assert.AreEqual(1, 1); // Or whatever you want to actually assert.
}
}
編輯:
或者
[TestMethod]
public void Test1()
{
try{
// You're code to test.
AreEqual(1, 1); // Or whatever you want to actually assert.
}
catch(Exception ex){
Assert.Fail();
}
}
有時候我想測試特定的異常性的價值,在這種情況下我有時會選擇不使用的ExpectedException屬性。
相反,我用下面的辦法(例子):
[Test]
public void MyTestMethod() {
try {
var obj = new MyClass();
obj.Foo(-7); // Here I expect an exception to be thrown
Assert.Fail(); // in case the exception has not been thrown
}
catch(MySpecialException ex) {
// Exception was thrown, now I can assert things on it, e.g.
Assert.AreEqual(-7, ex.IncorrectValue);
}
}
在不引發的異常測試不會失敗。 – 2010-08-12 11:31:23
@Stefan - 已更新帖子。乾杯:) – 2010-08-12 11:34:40
好吧,但它應該是另一種方式:在嘗試和失敗的最後一行失敗。 – 2010-08-12 11:43:37