Introduction
Testing exceptions in NUnit (a popular unit testing framework for C#) involves verifying that a specific exception is thrown when a certain piece of code is executed. Here’s an example of how you can write NUnit tests to verify that an exception is thrown:
Suppose you have a simple class with a method that throws an exception:
public class Calculator
{
public int Divide(int dividend, int divisor)
{
if (divisor == 0)
throw new DivideByZeroException("Cannot divide by zero.");
return dividend / divisor;
}
}
Now, let’s write NUnit tests to test this class and its method:
Step 1: Install NUnit and NUnit3TestAdapter
In your NUnit test project, you need to install the NUnit
and NUnit3TestAdapter
NuGet packages.
Step 2: Write NUnit Test Cases
Create a test class and write test methods using the TestCase
attribute to specify test cases and expected outcomes. Use the Assert.Throws
method to verify that a specific exception is thrown.
using NUnit.Framework;
using System;
[TestFixture]
public class CalculatorTests
{
private Calculator _calculator;
[SetUp]
public void Setup()
{
_calculator = new Calculator();
}
[Test]
public void Divide_ValidValues_ReturnsQuotient()
{
int result = _calculator.Divide(10, 2);
Assert.AreEqual(5, result);
}
[Test]
public void Divide_DivideByZero_ThrowsDivideByZeroException()
{
Assert.Throws<DivideByZeroException>(() => _calculator.Divide(10, 0));
}
}
In the Divide_DivideByZero_ThrowsDivideByZeroException
test, we use the Assert.Throws
method to ensure that calling the Divide
the method with a divisor of zero throws a DivideByZeroException
.
Step 3: Run NUnit Tests
Run your NUnit tests using a test runner (such as the built-in test runner in Visual Studio, ReSharper, or the dotnet test
command-line tool). The test runner will execute your tests and report the results.
The above example demonstrates how to test for expected exceptions using NUnit in C#. You can apply similar techniques to test exceptions in other scenarios as well. Remember that proper exception handling and testing play a critical role in ensuring the reliability and robustness of your code.