如果测试执行失败,我无法设置将屏幕截图附加到 TestResult 的正确方法
该框架是使用 Visual Studio 2015、Selenium v3.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/