Monday, January 30, 2023

customized reports in bdd cucumber framework in c#

[Binding]
public class CustomReportSteps
{
    [AfterTestRun]
    public static void AfterTestRun()
    {
        var jsonFiles = Directory.GetFiles(Path.GetFullPath("TestResult"), "*.json", SearchOption.AllDirectories);

        var reports = new List<Report>();
        foreach (var jsonFile in jsonFiles)
        {
            var content = File.ReadAllText(jsonFile);
            var report = JsonConvert.DeserializeObject<Report>(content);
            reports.Add(report);
        }

        var htmlReport = GenerateHtmlReport(reports);
        File.WriteAllText("CustomReport.html", htmlReport);
    }

    private static string GenerateHtmlReport(List<Report> reports)
    {
        var builder = new StringBuilder();
        builder.Append("<html><head><title>Custom Cucumber Report</title></head><body>");
        builder.Append("<table><tr><th>Feature</th><th>Scenario</th><th>Result</th><th>Time</th></tr>");

        foreach (var report in reports)
        {
            foreach (var feature in report.Features)
            {
                foreach (var scenario in feature.Elements)
                {
                    var result = scenario.Steps.All(step => step.Result.Status == "passed") ? "Passed" : "Failed";
                    var time = scenario.Steps.Sum(step => step.Result.Duration);

                    builder.Append("<tr>");
                    builder.Append($"<td>{feature.Name}</td>");
                    builder.Append($"<td>{scenario.Name}</td>");
                    builder.Append($"<td>{result}</td>");
                    builder.Append($"<td>{time}</td>");
                    builder.Append("</tr>");
                }
            }
        }

        builder.Append("</table></body></html>");
        return builder.ToString();
    }
}

public class Report
{
    public List<Feature> Features { get; set; }
}

public class Feature
{
    public string Name { get; set; }
    public List<Element> Elements { get; set; }
}

public class Element
{
    public string Name { get; set; }
    public List<Step> Steps { get; set; }
}

public class Step
{
    public Result Result { get; set; }
}

public class Result
{
    public string Status { get; set; }
    public int Duration { get; set; }
}

No comments:

Post a Comment