Fundamentals of Unit Testing: Understand ExpectedException in Unit Testing

This is the “Fundamentald of Unit Testing” article series. Our previous article was an introduction to unit testing. We have learned why unit testing is very important and defined the procedure for Test Driven Development. You can read it here.

This article explains the “ExpectedException” attribute in unit testing. This attribute is used when we know that a function may throw some kind of exception. For example, if we know that the specific function will throw some kind of exception then we can use the “ExpectedException” attribute. Let's try to understand this with an example. Create one class library and unit test project and provide a reference to it. If you are very new in unit testing then I suggest you to go through the first two articles of this series.

Anyway, here is our code that we will test using a unit test application.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6. namespace TestProjectLibrary  
  7. {  
  8.     public class MathClass  
  9.     {  
  10.         public int Devide(int a, int b)  
  11.         {  
  12.             return a / b;  
  13.         }  
  14.     }  
  15. }  
As we are seeing, here we are performing a division operation and if the “b” value is zero then it will throw a “DivideByZero” exception.

Fine, now let's implement the unit test function to test the code, here is the sample example.

  1. using System;  
  2. using Microsoft.VisualStudio.TestTools.UnitTesting;  
  3. using TestProjectLibrary;  
  4. namespace UnitTest  
  5. {  
  6.     [TestClass]  
  7.     public class UnitTest1  
  8.     {  
  9.         [TestMethod]  
  10.         public void TestMethod1()  
  11.         {  
  12.             MathClass ObjMath = new MathClass();  
  13.             int Result = ObjMath.Devide(10, 0);  
  14.             Assert.AreEqual(10, Result);  
  15.         }  
  16.     }  
  17. }  
Ok, now let's run the unit test and we will see the following output.
 
run the unit test

We are seeing that the test has failed because we are supplying "0" as the b value and in the rules of division it will return infinite and in programming terms it's a dividing by zero exception. We will now decorate our test method with the "DivideByZero" attribute, so that the method will know that if the targeted method throws a "Divide by zero" exception then it's our expected exception.

Here is our modified code.
 
modified code

And we are seeing that the test has passed even if we supply 0 as the "b" value because now our unit test function knows that if the targeted function throws a "DivideByZero" exception then it's okay.

Conclusion


In this example we have learned to use the “ExpectedException” attribute in unit testing. I hope it will add some extra knowledge in your unit test learning. Happy coding.


Similar Articles