There are basically two approaches you can take, depending on your situation.
Situation 1: Extending WebDriver is not a realistic option.
This is the most common situation. Most developers working with Selenium in real-work situations who want a handy way of telling if a WebDriver has quit are working in an already established testing framework, and trying to refactor the framework to ensure that only your custom extensions of WebDrivers are used is probably more trouble than it's worth.
In this case, Sajan's answer and Gili's recommendation of his answer won't be useful, because overriding RemoteWebDriver#stopClient()
is not an option. (Besides, even if it was, most people are looking for a simple answer.)
As long as you are only using standard implementations of WebDriver that come with Selenium (FirefoxDriver, ChromeDriver, InternetExplorerDriver, SafariDriver, etc.), you can cast the WebDriver to a RemoteWebDriver and then check if the sessionId is null (Pat was on the right track, but a direct call to sessionId is better than using toString()
).
public static boolean hasQuit(WebDriver driver) {
return ((RemoteWebDriver)driver).getSessionId() == null;
}
This answer should be good for 95% of all cases, because how often are you going to use a WebDriver that doesn't implement RemoteWebDriver? (Not very often.)
Situation 2: You CAN realistically extend your WebDriver.
This situation is less common, but perhaps you are either:
(a) Working with a well-designed and abstracted framework, or
(b) Starting a selenium test framework from scratch.
In this case, you can create your own interface that extends WebDriver:
public interface CustomDriver extends WebDriver {
boolean hasQuit();
}
And then you can extend standard WebDrivers like so (in this example, ChromeDriver):
public class CustomChromeDriver extends ChromeDriver implements CustomDriver {
boolean hasQuit = false;
@Override
public boolean hasQuit() {
return hasQuit;
}
@Override
public void stopClient() {
super.stopClient();
hasQuit = true;
}
}