我们可以通过两种方法在单元测试中验证异常。
使用 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(() => 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# 单元测试中抛出的异常?的详细内容,更多请关注【创想鸟】其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。
发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2431257.html