The WebDriver interface does not contain the getScreenshotAs() method, because it is possible that the web disk is unable to take screenshots - for example, in-memory drivers that do not display the page at all, for example, HtmlUnitDriver .
To have this method, the driver must implement the TakesScreenshot interface, which allows it ... well ... to take screenshots.
Therefore, you must tell the program that you want to take a screenshot, and that you are absolutely sure that you can do it. This is what is for the (TakesScreenshot)driver . In Java it is called casting , and it literally translates to "I know that this driver instance is capable of TakesScreenshot a screenshot, please enter it into the TakesScreenshot type."
If your promotion is successful, everything will be fine, and the driver object will be launched during the execution of the TakesScreenshot instance. However, if your listing does not work, you will get ClassCastExcepion at runtime.
Some examples:
// We already know this is ok, because FirefoxDriver implements (IS-A) TakesScreenshot. WebDriver driver = new FirefoxDriver(); TakesScreenshot screenshottingDriver = (TakesScreenshot)driver; // This will fail at run-time, because HtmlUnitDriver does not implement TakesScreenshot; WebDriver driver = new HtmlUnitDriver(); TakesScreenshot screenshottingDriver = (TakesScreenshot)driver; // You can use the `instanceof` operator to check: if (driver instanceof TakesScreenshot) { // we can be sure we can take screenshots, the cast will be safe ((TakesScreenshot)driver).getScreenshotAs(...); }
Petr janeΔek
source share