如何验证单元测试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.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),“TestException”))]中提到的异常相同,因此测试用例将通过。
热门推荐
1 训练狗狗工作
4 狗狗定点排便训练
5 狗狗训练吠叫
6 狗狗尿垫训练
7 狗狗训练座
8 狗狗训练攻略
9 狗狗训练记
10 做训练狗狗
11 狗狗训练词
12 狗狗谢谢怎么训练
13 狗狗训练如厕
14 狗狗太凶怎么训练
15 狗狗训练它
16 狗狗克制训练
17 训练基地狗狗
18 怎么样训练狗狗大小硬