【问题标题】:How to attach screenshot on test failure in MSTest?如何在 MSTest 中附加测试失败的屏幕截图?
【发布时间】:2019-09-24 21:10:00
【问题描述】:

如果测试执行失败,我无法设置正确的方法将屏幕截图附加到 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 从一个类传递到另一个类,但是我想不出一种方法来实际实现它

【问题讨论】:

    标签: c# selenium visual-studio-2015 mstest


    【解决方案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")); 将路径添加到测试结果/将其写入跟踪;

    【讨论】:

    • 您好@OriBr,感谢您的意见。我可以这样做,但这仍然不能解决必须通过 TestContext 才能在 EventListener 中使用 TestContext.AddResultFile 的问题,这是我主要关心的问题。
    • 每次截屏时,您可以将文件路径保存在全局变量中。获得此路径后,您可以从 TestCleanUp 访问它并添加它。不要忘记使用 Guid 对象生成唯一路径
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-04
    • 2021-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多