There are two ways that we can verify an exception in unit testing.
Let us consider a StringAppend method which throws an exception needs to be tested.
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"); } } }
example, we are calling the StringAppend method using Assert.ThrowsException and exception type and message are validated. 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"); } } }
example, we are using ExpectedException attribute and specifying the type of the expected exception. Since the StringAppend method throw the same type of exception which is mentioned in [ExpectedException(typeof(Exception), "Test Exception")] the test case will pass.