How do I use Assert to verify that an exception has been thrown with MSTest?

Matheus Mello
Matheus Mello
September 2, 2023
Cover Image for How do I use Assert to verify that an exception has been thrown with MSTest?

🎯 How to Use Assert to Verify That an Exception Has Been Thrown with MSTest

If you're using MSTest (Microsoft.VisualStudio.TestTools.UnitTesting) for your unit tests, you might have come across the need to verify that an exception is thrown in your code. Fortunately, MSTest provides a straightforward way to tackle this scenario using the Assert class. In this guide, we'll explore common issues and provide easy solutions to help you effectively use Assert to validate exceptions. Let's dive in! 💪

🧠 Understanding the Challenge

Before we jump into the solution, let's go over the challenge we're facing. We need to ensure that an exception is thrown when running a specific piece of code. This is essential for verifying the correctness of our program and making sure it handles exceptional situations properly.

📚 The Assert.ThrowsException Method

To address this challenge, MSTest offers the Assert.ThrowsException method, which is specifically designed to check for exceptions. This method allows us to capture and validate exceptions during our unit tests, ensuring that the expected exceptions are thrown when executing specific code.

📝 Syntax:

Assert.ThrowsException<ExpectedExceptionType>( () => {
    // code that should throw an exception
});

✅ Example:

Consider the following scenario, where we want to verify that a specific method throws an InvalidOperationException:

[TestMethod]
public void TestMethod_ExceptionThrown()
{
    Assert.ThrowsException<InvalidOperationException>(() => {
        // code that should throw an InvalidOperationException
        throw new InvalidOperationException("This is an exception.");
    });
}

In this example, we wrap the code that should throw an exception within the () => { } lambda expression. The Assert.ThrowsException method ensures that an InvalidOperationException is thrown, allowing the unit test to pass. If the specified exception is not thrown or a different exception is thrown, the test will fail.

💡 Pro Tips

1️⃣ Verifying Exception Messages

In some cases, it's not only essential to ensure that an exception is thrown but also to validate the exception message. You can achieve this by storing the exception object and performing additional checks using the familiar Assert methods.

[TestMethod]
public void TestMethod_ExceptionMessage()
{
    InvalidOperationException ex = Assert.ThrowsException<InvalidOperationException>(() => {
        // code that should throw an InvalidOperationException
        throw new InvalidOperationException("This is an exception.");
    });

    // Additional assertion to verify the exception message
    Assert.AreEqual("This is an exception.", ex.Message);
}

2️⃣ Handling Expected Exceptions

Sometimes, your code might throw an exception that is expected behavior. In such cases, you can use Assert.ThrowsException in conjunction with another Assert method to ensure that no exception is thrown.

[TestMethod]
public void TestMethod_NoExceptions()
{
    // code that should not throw any exceptions
    Assert.ThrowsException<AssertFailedException>(() => {
        // code that should not throw an exception
    });
}

Here, we use the AssertFailedException to verify that no exceptions are thrown. If any exception is thrown, the test will fail.

📣 Wrap Up and Engage

Now that you understand how to use the Assert.ThrowsException method with MSTest, you can easily verify that exceptions are thrown in your code. Remember the key points:

  1. Utilize Assert.ThrowsException<ExpectedExceptionType> to validate that a specific exception is thrown.

  2. Add additional Assert statements to validate exception messages or absence of exceptions.

Try implementing these techniques in your unit tests and see the difference they make in ensuring the stability and correctness of your code.

Have you encountered any challenges or interesting scenarios while working with exception verification in MSTest? Share your experiences, thoughts, and questions in the comments section below. Let's learn from each other! 🤝

Take Your Tech Career to the Next Level

Our application tracking tool helps you manage your job search effectively. Stay organized, track your progress, and land your dream tech job faster.

Your Product
Product promotion

Share this article

More Articles You Might Like

Latest Articles

Cover Image for How can I echo a newline in a batch file?
batch-filenewlinewindows

How can I echo a newline in a batch file?

Published on March 20, 2060

🔥 💻 🆒 Title: "Getting a Fresh Start: How to Echo a Newline in a Batch File" Introduction: Hey there, tech enthusiasts! Have you ever found yourself in a sticky situation with your batch file output? We've got your back! In this exciting blog post, we

Cover Image for How do I run Redis on Windows?
rediswindows

How do I run Redis on Windows?

Published on March 19, 2060

# Running Redis on Windows: Easy Solutions for Redis Enthusiasts! 🚀 Redis is a powerful and popular in-memory data structure store that offers blazing-fast performance and versatility. However, if you're a Windows user, you might have stumbled upon the c

Cover Image for Best way to strip punctuation from a string
punctuationpythonstring

Best way to strip punctuation from a string

Published on November 1, 2057

# The Art of Stripping Punctuation: Simplifying Your Strings 💥✂️ Are you tired of dealing with pesky punctuation marks that cause chaos in your strings? Have no fear, for we have a solution that will strip those buggers away and leave your texts clean an

Cover Image for Purge or recreate a Ruby on Rails database
rakeruby-on-railsruby-on-rails-3

Purge or recreate a Ruby on Rails database

Published on November 27, 2032

# Purge or Recreate a Ruby on Rails Database: A Simple Guide 🚀 So, you have a Ruby on Rails database that's full of data, and you're now considering deleting everything and starting from scratch. Should you purge the database or recreate it? 🤔 Well, my