Home >Backend Development >C#.Net Tutorial >How to verify exceptions thrown in C# unit tests?

How to verify exceptions thrown in C# unit tests?

WBOY
WBOYforward
2023-08-27 10:49:061003browse

如何验证 C# 单元测试中抛出的异常?

We can verify exceptions in unit tests in two ways.

  • Use Assert.ThrowsException
  • Use the ExpectedException property.

Example

Let us consider a StringAppend method that needs to be tested for throwing an exception.

using System;
namespace DemoApplication {
   public class Program {
      static void Main(string[] args) {
      }
      public string StringAppend(string firstName, string lastName) {
         throw new Exception("Test Exception");
      }
   }
}

Using Assert.ThrowsException

using System;
using DemoApplication;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace DemoUnitTest {
   [TestClass]
   public class DemoUnitTest {
      [TestMethod]
      public void DemoMethod() {
         Program program = new Program();
         var ex = Assert.ThrowsException<Exception>(() => program.StringAppend("Michael","Jackson"));
         Assert.AreSame(ex.Message, "Test Exception");
      }
   }
}

For example, we use Assert.ThrowsException to call the StringAppend method and verify the exception type and message. So the test case will pass.

Using the ExpectedException attribute

using System;
using DemoApplication;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace DemoUnitTest {
   [TestClass]
   public class DemoUnitTest {
      [TestMethod]
      [ExpectedException(typeof(Exception), "Test Exception")]
      public void DemoMethod() {
         Program program = new Program();
         program.StringAppend("Michael", "Jackson");
      }
   }
}

For example, we use the ExpectedException attribute and specify the type of expected exception. Since the StringAppend method throws the same type of exception as mentioned in [ExpectedException(typeof(Exception), "Test Exception")], the test case will pass.

The above is the detailed content of How to verify exceptions thrown in C# unit tests?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete