0
votes

I currently have a very simple Selenium Specflow framework which open a Chrome or Firefox browser. I want to add an AfterTestRun hook to quit and dispose of the driver so that the browser closes correctly.

LoginPage.cs:

[Binding]
public class LoginPage
{
    private IWebDriver Driver { get; set; }

    [Given("I open a (.*) browser with a (.*) resolution (.*)")]
    public IWebDriver CreateBrowserInstance(Browser browser, BrowserResolution resolution, bool headless)
    {
        switch(browser)
        {
            case Browser.Chrome:
                Driver = StaticWebDriverFactory.GetChromeWebDriver(resolution, headless);
                return Driver;
            case Browser.Firefox:
                Driver = StaticWebDriverFactory.GetFirefoxWebDriver(resolution, headless);
                return Driver;
            default:
                throw new PlatformNotSupportedException($"{browser} is not currently supported.");
        }
    }
}

Hooks.cs

[Binding]
public class Hooks
{
    private IWebDriver Driver { get; }

    [AfterTestRun]
    public void AfterTestRun()
    {
        Driver.Quit();
        Driver.Dispose();
    }
}

When I don't have the Hooks file, the test will open the browser as expected. However we I add it in and run the test, the test is skipped. I am not sure where I am going wrong with the hooks.

Edit:

I tried to put the [AfterScenario] in the LoginPage.cs file and it worked as expected.

I am not sure why I cannot have my test hooks in a separate file as they will be used by all tests/pages. Am I looking at this the wrong way?

1
In your LoginPage class you need to call hooks inside constructor.I can't see any constructor for LoginPage class.KunduK

1 Answers

1
votes

I am not sure why I cannot have my test hooks in a separate file as they will be used by all tests/pages. Am I looking at this the wrong way?

You can have your test hooks in a separate file [That's the best practice] and also multiple times. The test runner will execute all the hooks methods.

The binding methods for before/after feature and before/after test run events must be static

Now in your case debug and check whether your Driver property is having the instance of webdriver which you want to close in aftertest run method.

By looking at your code it seems like Driver property in your Hooks class doesn't have the current instance of your webdriver.