Why to take screenshot is required in automation?
- Screenshot helps us to understand the flow of application whether application is behaving correctly or not.
- It helps as while doing cross browser testing.
- Another use is, while doing headless testing, you will not see actual GUI screen, but it will run on backend (ex – by using HTMLUnitBrowser ), in that case, we can track failed tests.
- Screen shot is required in failure, so that we will get to know why the test case is failed.
To take screen shot in selenium, we have one predefined interface known as TakesScreenshot, we can not create object of an interface in java. So we need to typecast it to Webdriver object.
TakesScreenshot ts = (TakesScreenshot)driver;
Explanation: We can’t create object directly so typecast and then create.
File srcFile = ts.getScreenShotAs(OutPutType.FILE);
Explanation: Use the object created, then get screenshot as file & assign it to the File variable.
FileUtils.copyFile(srcFile, new File(“./ScreenShots/image1.png”);
Explanation: Now you need to copy the srcFile, so use FileUtils class, then give source file & destination file. In destination file “.” (dot) refers to the current working directory.
Below is the sample piece of code which shows how to take a screenshot in selenium.
To know how to take screenshot of failed test case only, refer below post.
Refer – How to take screen shot of failed test case only? <Link>
Hope this helps !!!!!