DemoBlazeAutomation / Hooks / Hooks.cs
Hooks.cs
Raw
using AventStack.ExtentReports;
using AventStack.ExtentReports.Gherkin.Model;
using BoDi;
using DemoBlazeAutomation.Utilities;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Edge;
using OpenQA.Selenium.Firefox;
using TechTalk.SpecFlow;


namespace DemoBlazeAutomation.Hooks
{
    [Binding]
    public class Hooks
    {
        private IWebDriver _driver;
        private readonly IObjectContainer _objectContainer;


        /// <summary>
        /// IObjectContainer se utiliza para compartir el objeto IWebDriver (en este caso) entre las clases de steps y los hooks.
        /// </summary>
        /// <param name="objectContainer"></param>
        public Hooks(IObjectContainer objectContainer)
        {
            _objectContainer = objectContainer;
        }


        [BeforeTestRun]
        public static void BeforeTestRun()
        {
            Console.WriteLine("Running before test run...");
            ExtentReport.ExtentReportInit();

        }


        [BeforeScenario]
        public void BeforeScenario(ScenarioContext scenarioContext)
        {
            // Configurar el navegador
            _driver = CreateDriver("chrome");
            _driver.Manage().Window.Maximize();
            _driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(5);
            _objectContainer.RegisterInstanceAs(_driver);
            //
            ExtentReport._scenario = ExtentReport._feature.CreateNode<Scenario>(scenarioContext.ScenarioInfo.Title);
        }

        public IWebDriver GetDriver()
        {
            return _driver;
        }


        [BeforeFeature]
        public static void BeforeFeature(FeatureContext featureContext)
        {
            Console.WriteLine("Running before feature...");
            ExtentReport._feature = ExtentReport._extentReports.CreateTest<Feature>(featureContext.FeatureInfo.Title);
        }



        [AfterScenario]
        public void AfterScenario()
        {
            // Cerrar el navegador
            Console.WriteLine("Running after scenario...");
            if (_driver != null)
            {
                _driver.Quit();
                _driver = null;
            }

        }

        [AfterTestRun]
        public static void AfterTestRun()
        {
            // Finalizar ExtentReports
            Console.WriteLine("Running after test run...");
            ExtentReport.ExtentReportTearDown();
        }

        [AfterFeature]
        public static void AfterFeature()
        {
            Console.WriteLine("Running after feature...");
        }

        [AfterStep]
        public void AfterStep(ScenarioContext scenarioContext)
        {
            Console.WriteLine("Running after step....");
            string stepType = scenarioContext.StepContext.StepInfo.StepDefinitionType.ToString();
            string stepName = scenarioContext.StepContext.StepInfo.Text;

            var driver = _objectContainer.Resolve<IWebDriver>();

            if (_driver == null)
            {
                Console.WriteLine("WebDriver es nulo. No se puede tomar la captura de pantalla.");
                return;
            }

            // Tomar captura de pantalla para todos los pasos (exitosos o fallidos)
            string screenshotPath = TakeScreenShot.addScreenshot(_driver, scenarioContext);

            // Crear nodo correspondiente al tipo de paso y agregar captura de pantalla
            if (scenarioContext.TestError == null)
            {
                //    ExtentReport._scenario.CreateNode(new GherkinKeyword(stepType), stepName).Pass("",
                //        MediaEntityBuilder.CreateScreenCaptureFromPath(screenshotPath).Build());

                ExtentReport._scenario.CreateNode(new GherkinKeyword(stepType), stepName);
            }
            else
            {
                ExtentReport._scenario.CreateNode(new GherkinKeyword(stepType), stepName).Fail(scenarioContext.TestError.Message,
                    MediaEntityBuilder.CreateScreenCaptureFromPath(screenshotPath).Build());
            }

            ////When scenario passed
            //if (scenarioContext.TestError == null)
            //{
            //    if (stepType == "Given")
            //    {
            //        ExtentReport._scenario.CreateNode<Given>(stepName);
            //    }
            //    else if (stepType == "When")
            //    {
            //        ExtentReport._scenario.CreateNode<When>(stepName);
            //    }
            //    else if (stepType == "And")
            //    {
            //        ExtentReport._scenario.CreateNode<And>(stepName);
            //    }
            //    else if (stepType == "Then")
            //    {
            //        ExtentReport._scenario.CreateNode<Then>(stepName);
            //    }
            //}

            ////When scenario fails
            //if (scenarioContext.TestError != null)
            //{
            //    if (stepType == "Given")
            //    {
            //        ExtentReport._scenario.CreateNode<Given>(stepName).Fail(scenarioContext.TestError.Message,
            //        MediaEntityBuilder.CreateScreenCaptureFromPath(TakeScreenShot.addScreenshot(driver, scenarioContext)).Build());
            //    }
            //    else if (stepType == "When")
            //    {
            //        ExtentReport._scenario.CreateNode<When>(stepName).Fail(scenarioContext.TestError.Message,
            //            MediaEntityBuilder.CreateScreenCaptureFromPath(TakeScreenShot.addScreenshot(driver, scenarioContext)).Build());
            //    }
            //    else if (stepType == "Then")
            //    {
            //        ExtentReport._scenario.CreateNode<Then>(stepName).Fail(scenarioContext.TestError.Message,
            //            MediaEntityBuilder.CreateScreenCaptureFromPath(TakeScreenShot.addScreenshot(driver, scenarioContext)).Build());
            //    }
            //    else if (stepType == "And")
            //    {
            //        ExtentReport._scenario.CreateNode<And>(stepName).Fail(scenarioContext.TestError.Message,
            //            MediaEntityBuilder.CreateScreenCaptureFromPath(TakeScreenShot.addScreenshot(driver, scenarioContext)).Build());
            //    }
            //}
        }




        private IWebDriver CreateDriver(string browserName)
        {
            switch (browserName.ToLower())
            {
                case "chrome":
                    return new ChromeDriver();

                case "firefox":
                    return new FirefoxDriver();

                case "edge":
                    return new EdgeDriver();

                default: throw new Exception("Provided browser not supported");
            }
        }

    }
}