问题
I have seen somewhere we can use both
WebDriver driver = new FirefoxDriver()
or
SearchContext driver = new FirefoxDriver()
I am confused what is the difference between these two different interfaces?
回答1:
SearchContext
SearchContext is an interface which is the runtime container for contextual information for applications search. It contains search related meta information and can hold the reference to an external context that might be useful for the purpose of search as well as security. When used for searching, it holds a reference to AppsWebContext and can be obtained by getAppsContext. This context is passed to most applications plug-in code where custom implemenation can obtain runtime context information.
Interface SearchContext
SearchContext Interface have 2(two) subinterfaces:
- WebDriver
- WebElement
The implementing classes are:
- ChromeDriver
- EdgeDriver
- EventFiringWebDriver
- FirefoxDriver
- InternetExplorerDriver
- OperaDriver
- RemoteWebDriver
- RemoteWebElement
- SafariDriver
SearchContext has only two methods:
- findElement(By by)
- findElements(By by)
Example
An example of using SearchContext
is as follows:
@Override
public List<WebElement> findElements(SearchContext searchContext) {
List<WebElement> elements = new ArrayList<>();
try {
elements.add(this.findElement(searchContext));
} catch (Exception ex) {
}
return elements;
}
回答2:
This is the best blog which clearly answers this question: http://makeseleniumeasy.com/2017/04/02/hierarchy-of-selenium-classes-and-interfaces/
To add more:
SearchContext driver = new ChromeDriver();
Now if you like to use the abstract methods available with WebDriver like get(String url), close(), quit() etc. you have to downcast the driver instance to WebDriver level:
((WebDriver) driver).close();
回答3:
SearchContext is the superInterface of Webdriver and WebElement interfaces. As said in previous answers, searchContext have only two abstract methods.
findElement(By by)
findElements(By by)
If we create object using searchContext,only above specified method could be used.
WebDriver have many useful and required methods like get,getTitle,close,quit,switchTo,etc. These webdriver methods cannot be used directly unless you downcast to Webdriver. So, it is advisable to use
WebDriver driver = new FirefoxDriver()
来源:https://stackoverflow.com/questions/59745618/what-is-the-difference-between-searchcontext-and-webdriver-interfaces-in-seleniu