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
Release: 2023-08-27 10:49:06
forward
1000 people have browsed it

如何验证 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");
      }
   }
}
Copy after login

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");
      }
   }
}
Copy after login

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");
      }
   }
}
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template