Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle try-catch block in unit testing?

I want to write unit test for try catch block(C#).

Public ActionResult Index()
 {
     try
     {
         -------------
     }
     catch(Exception ex)
     {
           throw;
     }
}

As you can see that i am using try-catch block in my index method in controller.And while unit testing this method i want to cover try-catch block also.Where in catch block i am throwing the exception.But i don't have any idea about that.Can anyone suggest me the best way to handle try-catch block ? FYI,i am not specifying any exception type here,it wile fire/throw any exception.

like image 591
Pawan Avatar asked Apr 14 '14 07:04

Pawan


3 Answers

Check the ExpectedExceptionAttribute which is part of the framework.

http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.unittesting.expectedexceptionattribute.aspx

An example taken from the link:

[TestMethod()]
    [ExpectedException(typeof(System.DivideByZeroException))]
    public void DivideTest()
    {
        DivisionClass target = new DivisionClass();
        int numerator = 4;
        int denominator = 0;
        int actual;
        actual = target.Divide(numerator, denominator);
    }

Here, you are making a division by 0 which you know it's going to fail and throw and exception. If you were catching that exception on the code, then the test would fail because no exception woulg get thrown.

like image 154
Nahuel Ianni Avatar answered Sep 30 '22 19:09

Nahuel Ianni


Your catch block today is only re-throwing the exception. There is no real business logic like changing the status or adding error codes or anything else which needs testing. I think just testing the "try-catch block" and "throw" functionality that ships with the platform is an overkill.

like image 44
Amol Avatar answered Sep 30 '22 19:09

Amol


It depends on the unit testing framework being used. The frameworks with which I have worked provide a mechanism for verifying if an exception has been thrown or not by the system under test. Below are some frameworks and the related exception testing functionality.

Microsoft Unit Testing
ExpectedExceptionAttributeClass

[TestMethod]
[ExpectedException(typeof(Exception))]
public void Controller_Index_ThrowsException()
{
    var sut = new HomeController();
    sut.Index();
}

xUnit.net
How do I use xUnit.net?
Take a look at the What if I Expected an Exception? section.

[Fact]
public void Controller_Index_ThrowsException()
{
    var sut = new HomeController();
    Assert.Throws<Exception>(() => sut.Index());
}

[Fact]
public void Controller_Index_DoesNotThrowException()
{
    var sut = new HomeController();
    Assert.DoesNotThrow(() => sut.Index());
}

Additionally, xUnit.net provides a non-typed assertion method for testing exceptions being thrown.

like image 33
Ryan V Avatar answered Sep 30 '22 19:09

Ryan V