Skip to main content
 首页 » 编程设计

c#之如何编写异常处理的自动化测试

2024年02月23日20shangdawei

我有很多以下类型的代码(每个都从不同的表中获取数据)。

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()) 从数据库中获取数据并将其映射到列表。我们过去曾遇到过导致映射问题的记录问题,现在想立即记录这些问题,然后将它们发送给调用应用程序。除了异常处理之外,我对所有内容都有测试。我必须保留通用异常处理。

我正在使用或可以使用以下内容:

  • .Net 3.5
  • 对比 2008
  • NUnit 2.5.10.11092
  • 犀牛模拟 3.6

我的问题:

  • 我如何为 异常处理?
  • 我需要注入(inject) TableOneRowMapper 和 模拟它以便在调用时抛出异常?
  • 还有其他的吗 如何在不注入(inject)的情况下做到这一点?
  • 我不担心测试异常处理吗?

请您参考如下方法:

? 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 - 是的,因为它是一个依赖项,你应该注入(inject)它
  • 集成测试 - 否

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

不,否则这将是一个集成测试而不是单元测试

? Do I not worry about testing the exception handling?

???