我已经创建了一个基类,用于在C#中对失败的测试用例进行截图。我使用MSTest进行自动测试的specflow。但是,问题在于情景失败时,系统对情景计数的总数执行下面的AfterScenario
方法。例如,我在当前项目中有40个场景,假设场景#1正在运行,并且在场景#1执行后AfterScenario
方法将会调用,但对于每个时间场景,它将调用40次。SpecFlow AfterScenario每次执行的场景总数为
基类代码
[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'并且没有基类,它完美的工作。但我有一个问题...最初它没有工作,它仍然运行多次场景方法,因为我在基础项目中使用了“TakeScreenshot”类,在该基础项目中,我有脚本方法和我的测试项目引用了基础项目dll。问题是为什么'AfterScenario'在基础项目中多次运行?任何想法 –