Nunit BDD规范中的截图,并附在DevoOps测试结果中



我正在使用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测试结果上

您可能能够在后场景挂钩中实现这一点:

[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

最新更新