0

We use the following code to take screenshots in selenium.

WebDriver driver = new FirefoxDriver();
File src = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(src, new File("D:\\TestNGScreenshots\\screenshot.png"));

Here is what I understood:

  • TakesScreenshot is an interface that provides a method getScreenshotAs() to get screenshots.
  • But WebDriver doesn't extend this interface.
  • FirexfoxDriver class also doesn't implement this interface
  • The getScreenshotAs() method is implemented in a separate class RemoteWebDriver which implements TakesScreenshot.

Here we are casting the driver object to another interface TakesScreenshot and we are using it's method getScreenshotAs() which is implemented in a completely different class.

So if we want to use an interface methods which were implemented in some classes can we use them by casting our object (which was created from a class implementing to another interface) to that interface?

Also, if we create the driver like

FirefoxDriver driver = new FirefoxDriver()

We can't cast the Interface to the driver here. We have to use it like TakesScreenshot ts = drvier and then we can use the method getScreenshotAs(). Here also not sure what exactly happening?

Can someone explain please?

Thank you.

4

2 回答 2

1

In your example you are casting from WebDriver interface to TakesScreenshot interface. You can always cast from one interface to another because the Java compiler can't tell if the reference defined by one interface doesn't hold an object that implements other interfaces. This check is deferred to runtime where you will get ClassCastException if it fails.

FirefoxDriver may not directly implement TakesScreenshot but it extends RemoteWebDriver which does. Because of that FirefoxDriver IS-A TakesScreenshot as per the class javadocs. You can write following:

FirefoxDriver driver = new FirefoxDriver();
File src = driver.getScreenshotAs(OutputType.FILE);
于 2018-09-21T13:23:36.710 回答
0

截图

TakesScreenshot是公共接口,它提供了一种getScreenshotAs()截取屏幕截图并将其存储在指定位置的方法,并实现了以下类:

  • 火狐驱动
  • 铬驱动程序
  • InternetExplorer驱动程序
  • 边缘驱动程序
  • OperaDriver
  • Safari驱动程序
  • 事件触发WebDriver
  • 远程网络驱动程序
  • 远程WebElement

这意味着可以捕获屏幕截图并存储它的驱动程序是通过将驱动程序实例转换为TakesScreenshot类型实例来实现的。

举个例子:

public static void takeScreenShot() throws IOException{
    String path = "./ScreenShots/";
    File scrFile = ((TakesScreenshot)drive).getScreenshotAs(OutputType.FILE);
    FileUtils.copyFile(scrFile, new File(path + "Subbu" + ".jpg"));
    System.out.println("Screenshot Taken");
}
于 2018-09-21T14:35:46.020 回答