Using NUnit to test Exceptions

Using NUnit to test Exceptions

Introduction

Testing exceptions in C# using NUnit is an important aspect of ensuring your application handles error conditions correctly. NUnit provides a concise and expressive syntax for asserting that exceptions are thrown. However, every time I do this, I can never remember the syntax. So here it is so I can find it easily.

Example Scenario

Suppose you have a class Calculator with a method Divide that should throw an ArgumentException when the divisor is zero:

public class Calculator
{
    public double Divide(int dividend, int divisor)
    {
        if (divisor == 0)
        {
            throw new ArgumentException("Divisor cannot be zero");
        }

        return dividend / divisor;
    }
}

Writing NUnit Tests for Exceptions

1. Testing for an Exception

To test that an exception is thrown, you use the Assert.Throws<T> method where T is the type of the expected exception. Here’s how you can test the Divide method:

using NUnit.Framework;

[TestFixture]
public class CalculatorTests
{
    [Test]
    public void Divide_DivisorIsZero_ThrowsArgumentException()
    {
        // Arrange
        var calculator = new Calculator();

        // Act & Assert
        Assert.Throws<ArgumentException>(() => calculator.Divide(10, 0));
    }
}

In this test, you assert that calling Divide with a divisor of zero throws an ArgumentException.

2. Testing Exception Message

Sometimes, you might want to ensure that the exception message is correct. You can do this by capturing the exception in a variable and then asserting on its Message property:

[Test]
public void Divide_DivisorIsZero_ThrowsArgumentExceptionWithCorrectMessage()
{
    // Arrange
    var calculator = new Calculator();

    // Act
    var ex = Assert.Throws<ArgumentException>(() => calculator.Divide(10, 0));

    // Assert
    Assert.AreEqual("Divisor cannot be zero", ex.Message);
}

This test ensures that not only is an ArgumentException thrown, but it also has the correct error message.

3. Testing for No Exception

In some cases, you might want to explicitly assert that no exception is thrown. This can be done using Assert.DoesNotThrow:

[Test]
public void Divide_ValidInputs_DoesNotThrowException()
{
    // Arrange
    var calculator = new Calculator();

    // Act & Assert
    Assert.DoesNotThrow(() => calculator.Divide(10, 2));
}

This test checks that dividing two valid numbers does not result in an exception.

Conclusion

Using NUnit to test exceptions in C# helps you ensure that your application behaves as expected in error scenarios.

By asserting that specific exceptions are thrown under certain conditions, and that they contain the correct messages, you can create robust and reliable applications.

Remember, anticipating and properly handling error conditions is as important as implementing the main functionality of your application.

Perhaps now I have written this, I will remember the syntax…. but I doubt it.

You can find the official documentation here: – https://docs.nunit.org/articles/nunit/intro.html

Stephen

Hi, my name is Stephen Finchett. I have been a software engineer for over 30 years and worked on complex, business critical, multi-user systems for all of my career. For the last 15 years, I have been concentrating on web based solutions using the Microsoft Stack including ASP.Net, C#, TypeScript, SQL Server and running everything at scale within Kubernetes.