什么是最好的方法来避免尝试...抓住...终于......在我的单元测试中?

Bru*_* Li 5 unit-testing mstest coding-style

我正在使用Microsoft Test在VS 2010中编写许多单元测试.在每个测试类中,我有许多类似于下面的测试方法:

[TestMethod]
public void This_is_a_Test()
{
  try
  {
    // do some test here
    // assert
  }
  catch (Exception ex)
  {
    // test failed, log error message in my log file and make the test fail
  }
  finally
  {
    // do some cleanup with different parameters
  }
}
Run Code Online (Sandbox Code Playgroud)

当每个测试方法看起来像这样时,我觉得它有点难看.但到目前为止,我还没有找到一个很好的解决方案来使我的测试代码更加干净,尤其是finally块中的清理代码.有人可以给我一些建议吗?

提前致谢.

sll*_*sll 6

如果你真的想在测试执行时处理和记录异常,你可以用一个辅助方法包装这个标准模板,并使用如下所示的[*].

但是如果异常是测试用例的一部分,那么这是错误的方法,你应该使用测试框架提供的工具,例如NUnit提供了这样的帮助来测试异常:

Assert.Throws<ExceptionType>(() => { ... code block... });
Assert.DoesNotThrow(() => { ... code block... });
Run Code Online (Sandbox Code Playgroud)

并执行清理特殊方法属性[TestCleanup],[TestInitialize]并通过测试框架自动执行测试初始化​​和清理.

[*]我们的想法是将测试主体包装在一个委托中并传递给帮助器,该辅助器实际执行try/catch块中包含的测试执行:

// helper
public void ExecuteTest(Action test)
{
  try
  {
     test.Invoke();
  }
  catch (Exception ex)
  {
    // test failed, log error message in my log file and make the test fail
  }
  finally
  {
    // do some cleanup with different parameters
  }
}

[TestMethod]
public void This_is_a_Test_1()
{
   Action test = () =>
   {
       // test case logic
       // asserts
   };

   this.ExecuteTest(test);
}
Run Code Online (Sandbox Code Playgroud)