C# > Testing and Debugging > Unit Testing > Assertions
Asserting Exceptions with `Assert.Throws`
This snippet demonstrates how to use `Assert.Throws` in NUnit to verify that a specific exception is thrown under certain conditions. This is essential for testing error handling logic.
Concepts Behind Exception Assertions
Testing for exceptions is crucial to ensure your code handles errors gracefully. `Assert.Throws` (or equivalent methods in other testing frameworks) allows you to assert that a specific type of exception is thrown when a particular piece of code is executed. This verifies that error handling mechanisms are working correctly.
Code Example: Asserting a `DivideByZeroException`
This code defines a test case that asserts that a `DivideByZeroException` is thrown when the `Divide` method is called with a denominator of zero. The `Assert.Throws
using NUnit.Framework;
using System;
public class ExampleTests
{
public int Divide(int numerator, int denominator)
{
return numerator / denominator;
}
[Test]
public void Divide_ByZero_ThrowsException()
{
// Arrange
int numerator = 10;
int denominator = 0;
// Act & Assert
Assert.Throws<DivideByZeroException>(() => Divide(numerator, denominator));
}
}
Real-Life Use Case
Consider a function that processes user input. If the input is invalid (e.g., a negative value where only positive values are allowed), the function should throw an appropriate exception. `Assert.Throws` can be used to verify that this exception is thrown when invalid input is provided.
Best Practices
When to Use Exception Assertions
Use exception assertions whenever you want to verify that your code correctly handles error conditions and throws the appropriate exceptions in response to those errors. This is particularly important for methods that perform input validation, resource management, or complex calculations.
Interview Tip
Be prepared to discuss how to test exception handling in your code. Explain the importance of testing for exceptions and demonstrate your understanding of using `Assert.Throws` (or equivalent) to verify that exceptions are thrown correctly. Discuss the benefits of asserting specific exception types.
Alternatives
Different testing frameworks may have slightly different syntax for asserting exceptions. For example, MSTest uses `Assert.ThrowsException
Pros
Cons
FAQ
-
What if the code doesn't throw any exception?
If the code within the lambda expression in `Assert.Throws` does not throw an exception, the assertion will fail. -
Can I test for multiple exceptions in a single test?
It's generally recommended to have separate tests for each exception type to keep the tests focused and easier to debug. However, you could potentially use multiple `Assert.Throws` calls within a single test if necessary, but it's less common.