我创建了一个基类,用于为C#中失败的测试案例拍摄屏幕截图。我已经将specflow与MSTest一起用于自动化测试。但是,问题是方案失败时,系统将对方案计数总数运行以下AfterScenario
方法。例如,我当前的项目中有40个场景,可以说场景1正在运行,并且在场景n#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);
}
}
无论如何,有什么方法可以防止
AfterScenario
执行n个(场景计数)? 最佳答案
您的钩子被调用了很多次,因为您已经在基类上实现了它。
挂钩就像步骤绑定一样,是全局定义的。因此,您定义了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/