如何驗證 C# 單元測試中引發的異常?
有兩種方法可以在單元測試中驗證異常。
- 使用 Assert.ThrowsException
- 使用 ExpectedException 特性。
示例
讓我們考慮一個需要測試的引發異常的 StringAppend 方法。
using System;
namespace DemoApplication {
public class Program {
static void Main(string[] args) {
}
public string StringAppend(string firstName, string lastName) {
throw new Exception("Test Exception");
}
}
}使用 Assert.ThrowsException
using System;
using DemoApplication;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace DemoUnitTest {
[TestClass]
public class DemoUnitTest {
[TestMethod]
public void DemoMethod() {
Program program = new Program();
var ex = Assert.ThrowsException<Exception>(() => program.StringAppend("Michael","Jackson"));
Assert.AreSame(ex.Message, "Test Exception");
}
}
}例如,我們使用 Assert.ThrowsException 呼叫 StringAppend 方法,並驗證異常型別和訊息。因此,測試用例將透過。
使用 ExpectedException 特性
using System;
using DemoApplication;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace DemoUnitTest {
[TestClass]
public class DemoUnitTest {
[TestMethod]
[ExpectedException(typeof(Exception), "Test Exception")]
public void DemoMethod() {
Program program = new Program();
program.StringAppend("Michael", "Jackson");
}
}
}例如,我們使用 ExpectedException 特性並指定預期異常的型別。由於 StringAppend 方法引發了 [ExpectedException(typeof(Exception), "測試異常")] 中提到的相同型別的異常,因此測試用例將透過。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
JavaScript
PHP