Search code examples
c#mstest

Method for handling exceptions in mstest


I have a lot of tests writen in this format:

[TestMethod]
public void TestMethod1()
{
    try
    {
        DoShomething();
    }
    catch (Exception e)
    {
        WriteExceptionLogWithScreenshot( e );
    }
}

[TestMethod]
public void TestMethod2()
{
    try
    {
        DoAnotherShomething();
    }
    catch ( Exception e )
    {
        WriteExceptionLogWithScreenshot( e );
    }
}

I would like to unify this exception handling using something like

[TestCleanup]
public void Cleanup()
{
    // find out if an exception was thrown and run WriteExceptionLogWithScreenshot( e )
}

Then I could avoid writing try catch blocks in all methods.

Does mstest support something like this? anyone have an ideia about what I could do?


Solution

  • This is simpler:

        private void TryTest(Action action)
        {
            try
            {
                action();
            }
            catch (Exception e)
            {
                WriteExceptionLogWithScreenshot(e);
                throw;
            }
        }
    
        [TestMethod]
        public void TestMethod1()
        {
            TryTest(new Action(() =>
            {
                DoSomething();
            }
            ));
        }
    
        [TestMethod]
        public void TestMethod2()
        {
            TryTest(new Action(() =>
            {
                DoAnotherSomething();
            }
            ));
        }
    

    Be sure to re-throw the exception so the test fails. Notice the throw in the catch.