We can verify exceptions in unit tests in two ways.
Let us consider a StringAppend method that needs to be tested for throwing an exception.
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"); } } }
For example, we use Assert.ThrowsException to call the StringAppend method and verify the exception type and message. So the test case will pass.
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"); } } }
For example, we use the ExpectedException attribute and specify the type of expected exception. Since the StringAppend method throws the same type of exception as mentioned in [ExpectedException(typeof(Exception), "Test Exception")], the test case will pass.
The above is the detailed content of How to verify exceptions thrown in C# unit tests?. For more information, please follow other related articles on the PHP Chinese website!