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

时间:2019-05-07 08:38:29

标签: 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从一个类传递给另一个类,但是我想不出一种实际实现它的方法

1 个答案:

答案 0 :(得分:1)

最佳做法是使用事件侦听器包装驱动程序,并使用自己的服装屏幕快照获取程序覆盖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”)))将其写入跟踪中

相关问题