如何在单元测试中处理try-catch块?

Paw*_*wan 5 c# unit-testing moq try-catch

我想为try catch block(C#)编写单元测试。

Public ActionResult Index()
 {
     try
     {
         -------------
     }
     catch(Exception ex)
     {
           throw;
     }
}
Run Code Online (Sandbox Code Playgroud)

如您所见,我在控制器的索引方法中使用try-catch块。而在对该方法进行单元测试时,我也想覆盖try-catch块。在catch块中我抛出了异常。但是我没有有任何想法吗?有人可以建议我处理try-catch块的最佳方法吗?仅供参考,我在这里未指定任何异常类型,它将引发/引发任何异常。

Nah*_*nni 6

检查框架的一部分ExpectedExceptionAttribute。

http://msdn.microsoft.com/zh-CN/library/microsoft.visualstudio.testtools.unittesting.expectedexceptionattribute.aspx

来自链接的示例:

[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);
    }
Run Code Online (Sandbox Code Playgroud)

在这里,您正在将其除以0,就知道它将会失败并抛出异常。如果您在代码上捕获了该异常,则测试将失败,因为不会引发任何异常。