ExpectedException Attribute

Introduction

While working with unit tests, many times we face due to some type of exception our test fails, and these type of exceptions are known exceptions and we want to bypass these exception and want to pass our test, for fulfilling this nature there is very useful attribute called the ExpectedException Attribute. By using this attribute we can bypass the known type of exceptions. I am going to explain here with example, this example is simple and the understanding will be very clear. Let’s write a test case for divide by zero.

  1. using System;  
  2. using Microsoft.VisualStudio.TestTools.UnitTesting;  
  3.    
  4. namespace ExpectedException.Tests  
  5. {  
  6.     [TestClass]  
  7.     public class UnitTest1  
  8.     {  
  9.         [TestMethod]  
  10.         public void TestMethod1()  
  11.         {  
  12.         }  
  13.    
  14.         [TestMethod()]  
  15.         public void DivideByZeroTest()  
  16.         {  
  17.             int no = 4;  
  18.             int denominator = 0;  
  19.             int result;  
  20.             result = no / denominator;  
  21.    
  22.             Assert.AreNotEqual(0, result);  
  23.         }  
  24.     }  
  25. }

While we run this test, the test will fail because of the exception divide by zero. You can see the result in the following image.

see the result

Now rewrite our test method with the ExpectedException Attribute and again run the test.

  1. [TestMethod()]  
  2. [ExpectedException(typeof(System.DivideByZeroException))]  
  3. public void DivideByZeroTest()  
  4. {  
  5.     int no = 4;  
  6.     int denominator = 0;  
  7.     int result;  
  8.     result = no / denominator;  
  9.   
  10.     Assert.AreNotEqual(0, result);  
  11. }

If we run the test again, we will see the result as passed.

result

Conclusion

In this way we can bypass the ExpectedExceptions for the test cases.

Ebook Download
View all
Learn
View all