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 the negative scenario. In several test cases, there might be a situation or condition which throws an exception. In order to test those scenarios, we have to use 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 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. 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 is 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.

HostForLIFE.eu ASP.NET Core Hosting

European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.