mstest中处理异常的方法

Thi*_*ago 3 c# mstest

我有很多以这种格式编写的测试:

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

[TestMethod]
public void TestMethod2()
{
    try
    {
        DoAnotherShomething();
    }
    catch ( Exception e )
    {
        WriteExceptionLogWithScreenshot( e );
    }
}
Run Code Online (Sandbox Code Playgroud)

我想使用类似的东西来统一这个异常处理

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

这样我就可以避免在所有方法中编写 try catch 块。

mstest 支持这样的东西吗?有人知道我能做什么吗?

小智 5

最近我遇到了同样的问题。我发现,如果您使用 MSTest V2,您可以轻松扩展TestMethodAttribute 类并使用它,如下所示:

public class LoggedTestMethodAttribute : TestMethodAttribute
{
   public override TestResult[] Execute(ITestMethod testMethod)
   {
      var results = base.Execute(testMethod);
      //you can loop through results and call
      //WriteExceptionLogWithScreenshot(e);
   }
}
Run Code Online (Sandbox Code Playgroud)

我想当你不使用DataRow属性时,数组中总是只有一个结果。result然后您可以直接从项目的属性中获取异常TestFailureException

之后你只需要用[LoggedTestMethod]属性来装饰你的测试方法而不是[TestMethod]