我使用 Selenium 和 MSTest 进行了一系列自动化 UI 测试。
当测试失败时,我需要对 headless 浏览器进行屏幕截图,以便我可以诊断发生了什么。
目前我通过 try catch throw 来做到这一点,但需要在每个测试中重复。
[TestMethod]
public void TestThings()
{
try
{
// do things
Assert.Fail();
}
catch (Exception ex)
{
Driver.TakeScreenshot();
throw;
}
}
重复样板代码让我很难过,一定有更好的方法。是否有一些 onFailed 的东西我可以 Hook 来做这种事情?
最佳答案
可能最简单的方法是使用 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();
}
}
您可以将其放入基类中并从中继承所有测试类,这样您就不必将其复制到每个类中。
关于c# - 测试失败时执行代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30791285/