How to verify an exception that has been thrown in unit testing C#?


There are two ways that we can verify an exception in unit testing.

  • Using Assert.ThrowsException
  • Using ExpectedException Attribute.

Example

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 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");
      }
   }
}

example, we are calling the StringAppend method using Assert.ThrowsException and exception type and message are validated. So the test case will pass.

Using ExpectedException Attribute

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.

Updated on: 08-Aug-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements