【发布时间】:2014-12-30 18:54:16
【问题描述】:
我们正在尝试为每个步骤截取屏幕截图。
一切正常。但我们无法将屏幕截图与创建它们的步骤相关联。
我们想要的是FeatureContext.FeatureInfo 和ScenarioContext.ScenarioInfo 之类的东西。但在单个步骤级别。这样我们就可以相应地标记屏幕截图。
【问题讨论】:
我们正在尝试为每个步骤截取屏幕截图。
一切正常。但我们无法将屏幕截图与创建它们的步骤相关联。
我们想要的是FeatureContext.FeatureInfo 和ScenarioContext.ScenarioInfo 之类的东西。但在单个步骤级别。这样我们就可以相应地标记屏幕截图。
【问题讨论】:
编辑
添加了暴露的类:
ScenarioStepContext.StepInfo.Text 和 ScenarioStepContext.StepInfo.StepDefinitionType
这应该给你你想要的。
原答案
目前这是不可能的,尽管我刚刚(昨天)提交了一个pull request,它添加了这个功能。如果您对自己构建 specflow 感到满意,那么您可以克隆 my fork of the specflow repo 并切换到 ScenarioStepContext 分支,然后打开 TechTalk.Specflow_VS2013.sln 并自己构建项目。
首先,您需要为 nuget 包指定 specflow 的新版本号。打开SpecFlow.nuspec文件并编辑版本高于当前版本(我使用的是1.9.3.4),然后构建解决方案(如果你想构建这些版本,你需要安装VS2013 SDK和其他VS SDK )。
构建解决方案后,您需要从
安装 vsix\SpecFlow\IdeIntegration\Vs2013Integration\bin\Debug\TechTalk.SpecFlow.Vs2013Integration.vsix
然后从
添加nuget包\SpecFlow\Installer\NuGetPackages\bin\SpecFlow.1.9.3.4.nupkg.
完成此操作后,您将能够访问 ScenarioStepContext.StepInfo.Text 和 ScenarioStepContext.StepInfo.StepDefinitionType 以便能够使用当前步骤详细信息标记您想要的元素。
我们目前正在使用它,但请在主要 Specflow github 页面上的 PR 上提出任何问题,如果可以,我会修复它们。
【讨论】:
实现您自己的 LogTraceListener 可以让您获得当前的步骤定义:
public class LogTraceListener : ITraceListener
{
static public string LastGherkinMessage;
public void WriteTestOutput(string message)
{
LastGherkinMessage = message;
Console.WriteLine(message);
}
public void WriteToolOutput(string message)
{
Console.WriteLine(message);
}
}
这需要在 App.Config 的 SpecFlow 部分注册:
<specFlow>
<trace listener="MyNameSpace.LogTraceListener, MyAssemblyName" />
<unitTestProvider name="NUnit" />
</specFlow>
完成此操作后,LastGherkinMessage 属性将包含刚刚输入的步骤定义的文本。您可以从步骤定义中或从其他任何地方访问它。
【讨论】:
我有点晚了,但是这个方法会返回一个包含当前正在运行的步骤文本的字符串:
private static string GetCurrentPositionText()
{
int currentPositionText = 0;
try
{
var frames = new StackTrace(true).GetFrames();
if (frames != null)
{
var featureFileFrame = frames.FirstOrDefault(f =>
f.GetFileName() != null &&
f.GetFileName().EndsWith(".feature"));
if (featureFileFrame != null)
{
var lines = File.ReadAllLines(featureFileFrame.GetFileName());
const int frameSize = 20;
int currentLine = featureFileFrame.GetFileLineNumber() - 1;
int minLine = Math.Max(0, currentLine - frameSize);
int maxLine = Math.Min(lines.Length - 1, currentLine + frameSize);
for (int lineNo = currentLine - 1; lineNo >= minLine; lineNo--)
{
if (lines[lineNo].TrimStart().StartsWith("Scenario:"))
{
minLine = lineNo + 1;
break;
}
}
for (int lineNo = currentLine + 1; lineNo <= maxLine; lineNo++)
{
if (lines[lineNo].TrimStart().StartsWith("Scenario:"))
{
maxLine = lineNo - 1;
break;
}
}
for (int lineNo = minLine; lineNo <= maxLine; lineNo++)
{
if (lineNo == currentLine)
{
currentPositionText = lineNo - minLine;
return String.Format("->" + lines[lineNo]);
}
}
}
}
}
catch (Exception ex)
{
Debug.WriteLine(ex, "GetCurrentPositionText");
}
return String.Format("(Unable to detect current step)");
}
摘自 Gaspar Nagy 前段时间提出类似问题时发表的帖子,并稍作修改以仅返回当前步骤的字符串。
【讨论】: