How to write a unit test for exceptions in C#

Unit tests are a powerful tool every programmer should know about. I’ll show you how to create a unit test for exceptions in C#.

In this example, we want to test that when a stack is empty, if you ask for the element at the top, you will get an exception. Also, we are going to test in the same method, that when the stack has information, the method top returns the expected value.

The examples of code here uses NUnit framework.

So, the code is as follows:

       [Test]
        public void topTest() {
            Stack<int> stack = new Stack<int>();
            Assert.Throws<Exception>(() => stack.top());
            stack.push(1);
            Assert.AreEqual(1, stack.top());
            stack.push(2);
            Assert.AreEqual(2, stack.top());
            stack.push(3);
            Assert.AreEqual(3, stack.top());
        }

The text is self-explanatory. However, if you want to test for a specific type of exception, you can use the name of the class that represents the exception instead of ‘Exception’.

After executing the code above, you can see the following result if you are using Visual Studio.

How to write unit test for exceptions in CSharp output example 1
How to write unit test for exceptions in C# output example 1

Another thing you can do is to check the message of the exception.

I’m using my own stack implementation in C#, not the one that comes with the framework. Below is the method we are testing.

public T top() {
      if (info.Last != null)
            return info.Last.Value;
       else
          throw new Exception("The stack is empty");
}

As you can see, the message we expect when an exception happens in the method top is “The stack is empty”. We can create the unit test as follows.

[Test]
public void topTest2()
{
    Stack<int> stack = new Stack<int>();
    Exception ex = Assert.Throws<Exception>(() => stack.top());

    Assert.AreEqual("The stack is empty", ex.Message);
}

The difference is that now we should store the exception in a variable so that later we can compare the content of that variable with the specific message we are expecting. Assert.Throws will return the exception if any, so we use it to store it.

If you execute the code above, you can get the following output.

How to write unit test for exceptions in CSharp output example 2
How to write unit test for exceptions in C# output example 2

H@ppy coding!