如何在 C# 单元测试中验证抛出的异常?

csharpserver side programmingprogramming更新于 2025/6/28 19:07:17

在单元测试中,我们可以通过两种方式验证异常。

  • 使用 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(    }
   }
}

使用 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), "Test Exception")] 中提到的相同,因此测试用例将通过。


相关文章