Introduction
While working with unit tests, many times we face due to some type of exception our test fails, and these type of exceptions are known exceptions and we want to bypass these exception and want to pass our test, for fulfilling this nature there is very useful attribute called the ExpectedException Attribute. By using this attribute we can bypass the known type of exceptions. I am going to explain here with example, this example is simple and the understanding will be very clear. Let’s write a test case for divide by zero.
- using System;
- using Microsoft.VisualStudio.TestTools.UnitTesting;
-
- namespace ExpectedException.Tests
- {
- [TestClass]
- public class UnitTest1
- {
- [TestMethod]
- public void TestMethod1()
- {
- }
-
- [TestMethod()]
- public void DivideByZeroTest()
- {
- int no = 4;
- int denominator = 0;
- int result;
- result = no / denominator;
-
- Assert.AreNotEqual(0, result);
- }
- }
- }
While we run this test, the test will fail because of the exception divide by zero. You can see the result in the following image.
Now rewrite our test method with the ExpectedException Attribute and again run the test.
- [TestMethod()]
- [ExpectedException(typeof(System.DivideByZeroException))]
- public void DivideByZeroTest()
- {
- int no = 4;
- int denominator = 0;
- int result;
- result = no / denominator;
-
- Assert.AreNotEqual(0, result);
- }
If we run the test again, we will see the result as passed.
Conclusion
In this way we can bypass the ExpectedExceptions for the test cases.