Search code examples
c#unit-testingnunitautomated-testsrhino-mocks

How can I write an automated test for exception handling


I have a lot of the following type of code (each gets data from different tables).

public class TableOneDAO
{
    public TableOneDAO(IDbConnection dbConnection)
    {
        _dbConnection = dbConnection;
        _log = LogFacade.GetLog();
        _tableOneRowMapper = new TableOneRowMapper();
    }

    public IList<TableOneRecord> FindAll()
    {
        try
        {
            using (IDbCommand cmd = _dbConnection.CreateCommand())
            {
                cmd.CommandText = TableOneSql.FindAllSql();

                return _tableOneRowMapper.GetObjectList(cmd.ExecuteReader());
            }
        }
        catch (Exception exception)
        {
            _log.Error(exception.Message, exception);

            throw;
        }
    }

    private readonly IDbConnection _dbConnection;
    private readonly TableOneRowMapper_tableOneRowMapper;
    private readonly ILog _log;
}

_tableOneRowMapper.GetObjectList(cmd.ExecuteReader()) gets the the data from the database and maps it to a List. We have had past issues of records causing issues in the mapping and now want to log those right away and then trow them to the calling application. I have tests for everything but the exception handling. I must keep the generic exception handling in place.

I am using or have the following available to use:

  • .Net 3.5
  • VS 2008
  • NUnit 2.5.10.11092
  • Rhino Mocks 3.6

MY QUESTIONS:

  • How can I create automated tests (unit or integration) for the exception handling?
  • Do I need to inject the TableOneRowMapper and mock it so it throws an exception when called?
  • Are there any other ways to do this without injecting it?
  • Do I not worry about testing the exception handling?

Solution

  • ? How can I create automated tests (unit or integration) for the exception handling?

    // ensure that a given code block throws specific exception
    Assert.Throws<ExceptionType>(() => { code block to execute });
    
    // ensure that a given code block DOES NOT throw specific exception
    Assert.DoesNotThrow(() => { code block to execute });
    

    ? Do I need to inject the TableOneRowMapper and mock it so it throws an exception when called?

    • Unti test - yes, since it is a dependency you should inject it
    • Integration test - no

    ? Are there any other ways to do this without injecting it?

    No, otherwise it would be an integration test rather unit test

    ? Do I not worry about testing the exception handling?

    ???