What is the best way to avoid trying ... to catch ... finally ... in my unit tests?

I am writing a lot of unit tests in VS 2010 using Microsoft Test. In each test class, I have many testing methods similar to the ones below:

[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
  }
}

When each testing method looks like this, I fell on it as if ugly. But until I found a good solution to make my test code cleaner, especially the cleanup code in the finally block. Can anyone here give me some advice on this?

Thanks in advance.

+5
source share
3 answers

, , [*].

, , , , , NUnit :

Assert.Throws<ExceptionType>(() => { ... code block... });
Assert.DoesNotThrow(() => { ... code block... });

, [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);
}
+6

try-catch-finally ( , , ) tearDown ( MS Test, [TearDownMethod] [FixtureTearDown] - .

+1
0
source

All Articles