【问题标题】:Taking Screenshot in Nunit BDD specflow and attached to the DevoOps Test result在 Nunit BDD 规范流中截取屏幕截图并附加到 DevOps 测试结果
【发布时间】:2021-01-19 05:40:41
【问题描述】:

我正在使用 NUnit.net 核心 BDD 规范流程,我需要帮助来捕获失败场景步骤的屏幕截图并附加到 DevOps 中的 TFS 结果报告中。我有以下代码。

public bool loginpageelementpresent()
{
    try
    {
        return loginpageelement.Displayed;
    } 
    catch(Exception e)
    {
        var filePath = $"{TestContext.CurrentContext.TestDirectory}\\{TestContext.CurrentContext.Test.MethodName}.jpg";

        ((ITakeScreenshot)_driver).GetScreenshot().SaveAsFile(filePath);

        TestContext.AddTestAttachment(filePath);

        return false;
    }
}

使用此代码,我可以在 DevOps 中看到屏幕截图,但我想使用此代码适用于所有失败的场景步骤,有人可以向我解释如何使其更具动态性,因此如果任何场景步骤失败,它自动截屏并附加到 DevOps 测试结果中

【问题讨论】:

  • 只是想检查以下解决方法是否适合您?如果是,您可以accept the answer,这也可以让与您有同样困惑的其他人受益。另外,如果仍有任何疑问,请随时在下面发表评论:-)

标签: tfs nunit devops bdd specflow


【解决方案1】:

您也许可以在after scenario hook 中完成此操作:

[Binding]
public class SpecFlowHooks
{
    private readonly IObjectContainer container;
    private readonly ScenarioContext scenario;

    public TestContext TestContext { get; set; }

    private bool IsFailingScenario => scenario.TestError != null;

    public SpecFlowHooks(IObjectContainer container, ScenarioContext scenario)
    {
        this.container = container;
        this.scenario = scenario;
    }

    [BeforeScenario]
    public void CreateWebDriver()
    {
        // Create and configure the Selenium IWebDriver object
        var driver = new ChromeDriver() or FirefoxDriver() or EdgeDriver() or whatever you normally do

        // Make the web driver available to all step definitions, including this
        // hooks classes. Additionally flag this object as something BoDi should
        // dispose of at the end of each test.
        container.RegisterInstanceAs<IWebDriver>(driver, null, true);
    }

    [AfterScenario]
    public void RecordTestFailure()
    {
        if (IsFailingScenario)
        {
            var driver = container.Resolve<IWebDriver>();
            var photographer = (ITakeScreenshot)driver;
            var filePath = $"{TestContext.CurrentContext.TestDirectory}\\{TestContext.CurrentContext.Test.MethodName}.jpg";

            photographer.GetScreenshot()
                        .SaveAsFile(filePath);

            TestContext.AddTestAttachment(filePath);
        }
    }
}

假设向测试上下文添加附件确实会将屏幕截图添加到 DevOps 中的测试结果中。顺便说一句,这也是了解 SpecFlow 中的依赖注入以及如何在 SpecFlow 测试中正确初始化和管理 IWebDriver 对象的好机会。

我回答了另一个问题,它为您提供了初始化 Web 驱动程序的更完整图片,然后在您的步骤定义和 Selenium 页面模型中使用它:https://stackoverflow.com/a/56427437/3092298

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-21
    相关资源
    最近更新 更多