gpt4 book ai didi

c# - SpecFlow AfterScenario 每次执行场景总数

转载 作者:太空宇宙 更新时间:2023-11-03 12:26:11 26 4
gpt4 key购买 nike

我创建了一个基类,用于在 C# 中截取失败测试用例的屏幕截图。我将 specflow 与 MSTest 一起用于自动化测试。但是,问题是当场景失败时,系统会运行下面的 AfterScenario 方法来计算场景总数。例如,我当前的项目中有 40 个场景,假设场景#1 正在运行,在场景#1 执行后 AfterScenario 方法将调用,但它调用 40 次,每次场景。

基类代码

[Binding]
public abstract class TakeScreenshot : Steps
{
[AfterScenario]
public void AfterWebTest()
{
if (ScenarioContext.Current["run"]=="0")
{

if (ScenarioContext.Current.TestError != null)
{
TakeScenarioScreenshot(Tools.driver);
}
ScenarioContext.Current["run"] = "1";
}
}

private void TakeScenarioScreenshot(IWebDriver driver)
{
try
{
string fileNameBase = string.Format("{0}_{1}",
DateTime.Now.ToString("yyMMddHHmmssFFF") , ScenarioContext.Current.ScenarioInfo.Title);

var artifactDirectory = Path.Combine(Directory.GetCurrentDirectory(), "testresults");
if (!Directory.Exists(artifactDirectory))
Directory.CreateDirectory(artifactDirectory);

string pageSource = driver.PageSource;
string sourceFilePath = Path.Combine(artifactDirectory, fileNameBase + "_source.html");
File.WriteAllText(sourceFilePath, pageSource, Encoding.UTF8);
ITakesScreenshot takesScreenshot = driver as ITakesScreenshot;

if (takesScreenshot != null)
{
var screenshot = takesScreenshot.GetScreenshot();
string screenshotFilePath = Path.Combine(artifactDirectory, fileNameBase + "_screenshot.png");
screenshot.SaveAsFile(screenshotFilePath, ImageFormat.Png);
}
}
catch (Exception ex)
{
Console.WriteLine("Error while taking screenshot: {0}", ex);
}
}
}

这是我继承TakeScreenshot

的测试类
[Binding]
public class CheckTwoNumberAreEqual : TakeScreenshot
{

[Given(@"Check two numbers are same")]
public void GivenChecktwonumbersaresame()
{
Assert.AreEqual(2, 3);
}
}


[Binding]
public class TestAddNewUser : TakeScreenshot
{

[Given(@"Add two numbers and check answer")]
public void GivenAddtwonumbersandcheckanswer()
{
int a=2+3;
Assert.AreEqual(2, a);
}
}

有没有办法阻止 n(场景计数)的 AfterScenario 执行?

最佳答案

你的钩子(Hook)被调用了这么多次,因为你已经在基类上实现了它。

Hooks 类似于 Step 绑定(bind),它们是全局定义的。因此,您将 AfterScenario Hook 定义了多少次,您拥有多少个继承类。你只需要一次。请参阅此实现以满足您的要求:https://github.com/techtalk/SpecFlow.Plus.Examples/blob/master/SeleniumWebTest/TestApplication.UiTests/Support/Screenshots.cs

请查看 Gaspar Nagy 的博文:http://gasparnagy.com/2015/05/specflow-tips-problems-with-placing-step-definitions-to-base-classes/

关于c# - SpecFlow AfterScenario 每次执行场景总数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44886552/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com