This is the “Fundamentald of Unit Testing” article series. Our previous article was an introduction to unit testing. We have learned why unit testing is very important and defined the procedure for Test Driven Development. You can read it here.
- Fundamentals of Unit Testing: Getting Started With Unit Testing
- Fundamentals of Unit Testing: Test Your Application by Visual Studio Unit Test
- Fundamentals of Unit Testing: Understand AAA in Unit Testing
- Fundamental of Unit Testing: Understand AreEqual and AreEqual<T> in Unit Testing
- Fundamental of Unit Testing: Test Initialize and Test Setup
- Fundamentals of Unit Testing: Understand CollectionAssert() in Unit Testing
This article explains the “ExpectedException” attribute in unit testing. This attribute is used when we know that a function may throw some kind of exception. For example, if we know that the specific function will throw some kind of exception then we can use the “ExpectedException” attribute. Let's try to understand this with an example. Create one class library and unit test project and provide a reference to it. If you are very new in unit testing then I suggest you to go through the first two articles of this series.
Anyway, here is our code that we will test using a unit test application.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace TestProjectLibrary
- {
- public class MathClass
- {
- public int Devide(int a, int b)
- {
- return a / b;
- }
- }
- }
Fine, now let's implement the unit test function to test the code, here is the sample example.
- using System;
- using Microsoft.VisualStudio.TestTools.UnitTesting;
- using TestProjectLibrary;
- namespace UnitTest
- {
- [TestClass]
- public class UnitTest1
- {
- [TestMethod]
- public void TestMethod1()
- {
- MathClass ObjMath = new MathClass();
- int Result = ObjMath.Devide(10, 0);
- Assert.AreEqual(10, Result);
- }
- }
- }

We are seeing that the test has failed because we are supplying "0" as the b value and in the rules of division it will return infinite and in programming terms it's a dividing by zero exception. We will now decorate our test method with the "DivideByZero" attribute, so that the method will know that if the targeted method throws a "Divide by zero" exception then it's our expected exception.
Here is our modified code.

And we are seeing that the test has passed even if we supply 0 as the "b" value because now our unit test function knows that if the targeted function throws a "DivideByZero" exception then it's okay.
Conclusion
In this example we have learned to use the “ExpectedException” attribute in unit testing. I hope it will add some extra knowledge in your unit test learning. Happy coding.

Emrullah DanacıPosted Jul 24, 2018, 7:35 AM
Good job sourav
Gowtham RajamanickamPosted Apr 25, 2015, 5:29 AM
good