单元测试某些类型的异常

时间:2017-02-07 20:44:46

标签: c# unit-testing exception-handling

在我提出问题之前的一些背景知识。我目前正在开发一个从IBM DB2迁移到SQL Server的项目。不要过多详细介绍,但这个DB2链接服务器有时会与SQL服务器断开连接,这对链接服务器来说是正常的。我在代码中工作,并有一个流程设置,以便处理它。

无论如何,我正在尝试编写一个抛出DbException的测试方法(这是链接服务器未连接时抛出的异常)来测试我在链接服务器断开连接时编写的进程。有没有办法强制抛出某种类型的异常,以便我可以测试我的代码?

try catch块看起来像这样:

try
{
    //Regular Processing and attempt to update to DB2
}
catch (DbException ex)
{
    //Other processing to catch a linked server issue
}
catch (Exception ex) 
{
    //Even more processing for other exceptions
}

3 个答案:

答案 0 :(得分:2)

它与大多数单元测试的方法相同,通过接口注入依赖项,根据该接口将真正的数据库逻辑放在一个类中,并且 基于该接口测试另一个中的东西。

interface  IDBProcessor
{
   void Process()
}

class ThrowyClass : IDBProcessor
{
    public Exception ThrowThis {get; set;}
    public void Process() 
    {
        throw ThrowThis;
    }
}


void MyMethod(IDBProcessor processor)
{
  try
  {
    processor.Process()
  }
  catch (DbException ex)
  {
    //Other processing to catch a linked server issue
  }
  catch (Exception ex) 
  {
    //Even more processing for other exceptions
  }
}

然后在您的单元测试中,使用您想要的异常创建一个ThrowyClass并将其传入。(如果您愿意,有一些模拟框架可以帮助您免于创建Test类)。

[Test]
void MyThrowTest()
{
   var throwy = new ThrowyClass() { ThrowThis = new SomeSpecificException() };
   var myClass = new MyClass()
   myClass.MyMethod(throwy);
   // Assert what you expect
}

您必须根据具体应用自定义内容。您可能希望在" MyClass"

的构造函数中注入IProcessor

答案 1 :(得分:0)

你可以这样扔掉它:

throw new DbException();

答案 2 :(得分:0)

您应该查看IDbConnection并尝试Moq框架 您的代码应该如下

var dbConnectionMock = new Mock<IDbConnection>();
dbConnectionMock.Setup(x => x.Open())
                   .Callback(() => {
                           throw new SqlException();
                       }).Verifiable();

https://github.com/Moq/moq4/wiki/Quickstart