如果将屏幕截图逻辑放入TearDown方法中,则无论测试成功与否,它将在每次测试完成后调用。
我使用一个具有包装测试并捕获所有异常的功能的基类。当测试失败时,将捕获异常并截取屏幕截图。
我在所有Selenium测试中都使用了这个基类,它看起来像这样:
public class PageTestbase{ protected IWebDriver Driver; protected void UITest(Action action) { try { action(); } catch (Exception ex) { var screenshot = Driver.TakeScreenshot(); var filePath = "<some appropriate file path goes here>"; screenshot.SaveAsFile(filePath, ImageFormat.Png); // This would be a good place to log the exception message and // save together with the screenshot throw; } }}测试类如下所示:
[TestFixture]public class FooBarTests : PageTestbase{ // Make sure to initialize the driver in the constructor or SetUp method, // depending on your preferences [Test] public void Some_test_name_goes_here() { UITest(() => { // Do your test steps here, including asserts etc. // Any exceptions will be caught by the base class // and screenshots will be taken }); } [TearDown] public void TearDown() { // Close and dispose the driver }}


