Coding⏱️ 2 min read📅 2026-05-31

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

Verify exceptions with MSTest using Assert or other test classes.

Quick Answer: Use the 'Assert.Throws' method to verify that an exception has been thrown in your MSTest tests.

To verify that an exception has been thrown when using MSTest, you can use the Assert.Throws method, where T is the type of exception you're expecting. For example:

💡 Using Assert.Throws

  • Assert.Throws MyMethod();

🚀 Verifying the Exception

Expected Behavior:

When you run this test, it should pass if an exception of type Exception is thrown from MyMethod.

Example Code:

using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Threading.Tasks;
namespace UnitTestProject
{
[TestClass]
}public class MyTest
{
[TestMethod]
public void MyMethod()
{
Assert.Throws(() => MyMethod());
}
private void MyMethod()
{
throw new Exception();
}
}

🎯 Final Words

By using Assert.Throws, you can ensure that the expected exception is thrown and catch any unexpected exceptions.

Did this fix your problem?

If not, try searching for specific error codes.

🔍 Search Error Database

❓ Frequently Asked Questions