如何验证 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"); } } }登录后复制