Testing The Exception Thrown In NUnit C#

In this article, we will learn how to test the exception thrown by the test code using NUnit in .Net. While doing unit testing, we write test cases for every possible positive as well as negative scenarios. In several test cases, there may be a situation or condition which throws an exception. In order to test those scenarios, we have to use the Asset.Throws method. Asset.Throws attempts to invoke a code snippet represented as a delegate in order to verify that it throws a particular exception.

For demonstration, I have already created a sample application, “BankingApp”, which is basically a .Net Core Class Library project. 

A test project named “BankingApp.Test” is also added to the solution. I am using NUnit for writing the unit test case. If you are new to NUnit, I recommend that you to go through the article below this series in case you are new to NUnit.

In the Account.cs class, I have a parameterized constructor and two methods in which one is for adding the amount i.e. depositAmount() method, and another for checking the balance amount (i.e. checkBalanceAmount() method). In case the amount to be deposited is either zero or less than that, an exception (ArgumentException) will be thrown.

In AccountTest.cs file, I have written a test case in which the amount to be deposited is “-100” i.e., less than zero.

Now, let’s run the test case from the Test Explorer.

On running the test case, an argument exception with a message i.e., “Amount to be deposit must be greater than zero” is thrown.

Let’s use the Assert.Throws() method and pass method as a delegate which is throwing the exception. In our case, it is depositAmount(). Assert.Throws require the exact type of exception which can be thrown. It returns the exception as well. With StringAssert.Contains() method, we can verify the expected exception text with the actual exception text.

Now, run the test case. You can see that our test case has passed. In this example, we verified that on passing the deposit amount 0 or less than zero, an exception is properly thrown to the user.


Similar Articles