c# - 如何在 MSTest 中附加测试失败的屏幕截图?

标签 c# selenium visual-studio-2015 mstest

如果测试执行失败,我无法设置将屏幕截图附加到 TestResult 的正确方法

该框架是使用 Visual Studio 2015、Selenium v​​3.141.0 设置的。

在传递中我尝试传递 TestContext作为 EventFiringWebDriver 的参数,因此我可以使用 EventFiringWebDriver.ExceptionThrown Event 附加屏幕截图

但是我不喜欢传递 TestContext,因为框架分为 Selenium 程序集(包含所有页面对象)和 Tests 程序集(包含所有测试用例)

TestBase.cs

[TestInitialize]
public void TestInitBase()
{
    SeleniumHelper = new HelperSelenium(TestContext);
}

HelperSelenium.cs

public HelperSelenium(TestContext testContext)
{
    Id = int.Parse(testContext.Properties["colegio"].ToString());
    WebDriver = new WebDriverSelector(testContext);
...
}

WebDriverSelector.cs

public WebDriverSelector(TestContext tc)
{
    testContext = tc;
...
    var firingWebDriver = new EventListeners(remoteDriver, testContext).GetWebDriver();
...

EventListeners.cs

public EventListeners(IWebDriver driver, TestContext testContext)
{
...

private static void UploadScreenShot()
{
    Screenshot ss = c.GetScreenshot();
    string path = Directory.GetCurrentDirectory() + "\\" +
        TestContext.TestName + "_" +
        contador + ".png";

        ss.SaveAsFile(path, ScreenshotImageFormat.Png);
        TestContext.AddResultFile(path);
}

我想跳过将 TestContext 从一个类传递到另一个类,但我想不出一种实际实现它的方法

最佳答案

最佳实践是使用事件监听器包装驱动程序,并使用您自己的服装屏幕截图程序覆盖 OnException 方法。 这样它就会识别任何地方的异常并自动截图,无需额外维护,

@Override
public void onException(Throwable throwable, WebDriver driver) {
    try
    {
        /* Take screenshot when exception happened. */
        File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
        /* save screenshot to file. */
        FileUtils.copyFile(scrFile, new File("C:\\Workspace\\webdriverEventListenerScreenshot.png"));
    }catch(IOException ex)
    {
        ex.printStackTrace();
    }
}

引用: https://www.dev2qa.com/webdriver-event-listener-take-screenshot-on-exception/

编辑: 您可以添加测试结果的路径/使用 (Trace.WriteLine("Path")); 将其写入跟踪;

关于c# - 如何在 MSTest 中附加测试失败的屏幕截图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56018626/

相关文章:

c# - WP7 应用程序中 ApplicationBar 中的切换按钮

python - 如何在同一选项卡中使用 selenium 函数? (在 python 上)

asp.net-mvc - Visual Studio 2015 是否支持旧版本的 MVC?

c++ - 使用 Visual Studio 2015 时如何通过 MSI 分发 VC redist?

c# - 更新后 Xamarin Forms 部署失败

c# - 在 C# 中实现基于字符串的日历

c# - 在 C# 中获取计算机名称而不引用 Microsoft.VisualBasic.dll

c# - ASP.Net体系结构,用于将上传内容传递给第三方

java - Selenium WebDriver : How to make sure element availability on Web Page?

javascript - 使用 Python + Selenium 通过 while 循环点击下一页