测试失败时执行代码

Execute code on test failure

我有一堆使用 Selenium 和 MSTest 的自动化 UI 测试。

当测试失败时,我需要截取无头浏览器的屏幕截图,以便诊断发生了什么。

目前我使用 try catch throw 来执行此操作,但它需要在每次测试中重复。

[TestMethod]
public void TestThings()
{
    try
    {
        // do things
        Assert.Fail();
    }
    catch (Exception ex)
    {
        Driver.TakeScreenshot();
        throw;
    }
}

重复的样板代码让我很难过,必须有更好的方法。是否有一些我可以挂钩的 onFailed 东西来做这种事情?

可能最简单的方法是使用 TestCleanup 并在那里检查测试结果:

// This will be set by the test framework.
public TestContext TestContext { get; set; }

[TestCleanup]
public void AfterTest()
{
    if (TestContext.CurrentTestOutcome != UnitTestOutcome.Passed) 
    {
        Driver.TakeScreenshot();
    }
}

您可以将它放在基础 class 中并从中继承所有测试 class,这样您就不必将它也复制到每个 class 中。