您好,欢迎访问一九零五行业门户网

如何验证 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.throwsexceptionusing 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)] 中提到的相同类型的异常,因此测试用例将通过。
以上就是如何验证 c# 单元测试中抛出的异常?的详细内容。
其它类似信息

推荐信息