SpecFlow AfterScenario每次执行时都会计算场景总数

时间:2017-07-03 13:14:54

标签: c# cucumber specflow

我已经创建了一个基类,用于在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 class

的测试类
[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);
    }
}

无论如何都要阻止AfterScenario执行n(场景计数)?

2 个答案:

答案 0 :(得分:1)

你的钩子被调用了很多次,因为你已经在基类上实现了它。

钩子就像步骤绑定,它是全局定义的。所以你定义了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/

答案 1 :(得分:0)

运行每个方案后,

AfterScenario用于执行。其他hook attributes更适合您的任务(可能是AfterTestRun)。