How to handle try-catch block in unit testing?
Asked Answered
A

4

8

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.

Amphibolite answered 14/4, 2014 at 7:1 Comment(2)
Why are you catching the exception just to rethrow it? Why not just take the try/catch away and unit test the unexpected behaviourGrecism
If you're not going to handle the exception, ej: NetworkException, ask the user to plug the network wire; let it bubble up.Petcock
U
5

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.

Urn answered 14/4, 2014 at 7:8 Comment(0)
M
4

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.

Mcclenon answered 16/4, 2014 at 5:14 Comment(1)
Yeah. This is the right answer to the question. If there was logic performed in the error handler before the throw, then that behavior could be verified.Angelicaangelico
M
3

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.

Monastic answered 16/4, 2014 at 21:3 Comment(0)
A
-1
try
    {
        ...
    }
catch (Exception ex)
    {
        _logger.Error(ex.Data, nameof(Create), ex.Message);
    }

I created this test for the above code, and it worked:

[Fact]
public async Task AccountTables_ThrowsException()
{
    //Arrange
    var logger = new Mock<ILoggerProvider<AccountTables>>();        
    var accountTable = new AccountTables(logger.Object);

    //Act
    await accountTable.Create(It.IsAny<string>(), CancellationToken.None);

    //Assert
    logger.Verify(z => z.Error(new Exception().Data, nameof(AccountTables.Create), It.IsAny<string>()), Times.Once);
}
Audie answered 12/2 at 16:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.