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.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace TestProjectLibrary

{

    public class MathClass

    {

        public int Devide(int a, int b)

        {

            return a / b;

        }

    }

}

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.

using System;

using Microsoft.VisualStudio.TestTools.UnitTesting;

using TestProjectLibrary;

namespace UnitTest

{

    [TestClass]

    public class UnitTest1

    {

        [TestMethod]

        public void TestMethod1()

        {

            MathClass ObjMath = new MathClass();

            int Result = ObjMath.Devide(10, 0);

            Assert.AreEqual(10, Result);

        }

    }

}

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.

Up Next
    Ebook Download
    View all
    Learn
    View all