How to Capture screenshot of failed test cases in Selenium using scala.


We write the selenium script for for the all test cases, some time its success and some time it failed. so better is to take the screen shot of failed test cases.

Automation provide the feature to take the screen shot of failed test cases. by this feature we get the exact idea where is our script failed. In selenium script is failed in different different scenario like when some locator has changed or some functionality has change and other thing is some our application issue.

for the failed the screen shot we should use the try catch block.we put the screen capture code inside the catch block. In my example, i am trying  to login in facebook and when i use wrong password then it should be giving a error so whenever i failed to login to facebook, screen shot will be captured.

Code for the capture the screen shot for failed test cases:

package SeleniumTest

import java.io.File

import org.apache.commons.io.FileUtils
 import org.openqa.selenium.OutputType
 import org.openqa.selenium.firefox.FirefoxDriver
 import org.openqa.selenium.remote.Augmenter
 import org.scalatest.FlatSpec
 import play.api.test.FakeApplication
 import play.api.test.Helpers.HTMLUNIT
 import play.api.test.Helpers.inMemoryDatabase
 import play.api.test.Helpers.running
 import play.api.test.TestServer
 import setup.Testsetup

class GenerateScreenshot extends FlatSpec with Testsetup {

running(TestServer(port, FakeApplication(additionalConfiguration = inMemoryDatabase())), HTMLUNIT) { browser =>

"Application" should "for facebook login" in {
 val driver = new FirefoxDriver()
 try {
 driver.manage().window().maximize()
 
driver.get("https://www.facebook.com/?stype=lo&jlou=AffcES-pE7ZOIAnyfQ0ri67sPADuX-tEjV5_ZeX7_JS13sVb- 
 
GRn0zhLg-nI_dvycS2rbtf6B8be-BuKlvZ336B-6KC_18qbGk5-6EbergdKJQ&smuh=57639&lh=Ac961TitQaPjB98k")
 // driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS)
 driver.findElementById("email").sendKeys("write.atfconnect1@gmail.com")
 driver.findElementById("pass").sendKeys("writea123")
 driver.findElementById("loginbutton").click()
 driver.findElementByCssSelector("BODY").getText().contains("Knoldus App")
 } catch {
 case ex: Exception =>
 val augmentedDriver = new Augmenter().augment(driver);
 val filed: File = driver.getScreenshotAs(OutputType.FILE);
 FileUtils.copyFile(filed, new File("/home/neeraj/Downloads/screencaptured.jpg"))
 }
 }

failedfacebooklogin

Screen Shot of failed test case:

screencaptured

This entry was posted in Scala. Bookmark the permalink.