
我们可以通过两种方法在单元测试中验证异常。
让我们考虑一个需要测试抛出异常的 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");
}
}
}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 方法,并验证异常类型和消息。因此测试用例将通过。
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")] 中提到的相同类型的异常,因此测试用例将通过。
以上就是如何验证 C# 单元测试中抛出的异常?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号