How to get the current executing step information in Specflow

前端 未结 3 2027
一向
一向 2021-01-12 11:10

We are trying to take screenshots for each step.

Everything works fine. But we are not able to correlate the screenshots to the steps which created them.

Wha

3条回答
  •  死守一世寂寞
    2021-01-12 12:09

    I'm a bit late to the party, but this method will return a string that contains the currently running step text:

    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)");
        }
    

    Taken from a post Gaspar Nagy made some time ago when a similar question was asked, and modified slightly to only return the string of the current step.

提交回复
热议问题