Monday, August 17, 2015

Capture Screen Shot on Failure Test cases using TestNG.








Hi guys in this post we are going to see, how to capture ScreenShot on Failure Test cases using TestNG.

Taking Screenshot on the failure is very important to understand the Bug clearly to the manual Testers and developers.

Scenarios for Testcase Failures:


  1. Unable to find elements in the Webpages
  2. Timeout to finding Webelements.
  3. Assertion Failure
  4. Application Error 

In this post we are going to see how this going to work in action.

In this Example we are going to forcefully fail the testcase  by Asserting the title.(Giving the wrong Title)


Steps:

  1. We are creating a new class to capture ScreenShots alone.

import java.io.File;
import java.io.IOException;

import javax.print.attribute.standard.MediaSize.Other;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;


public class CaptureScreenshot {
      
       public static void takescreenshot(WebDriver driver,String Screenshotname) throws IOException
       {
              TakesScreenshot takescreenshot=(TakesScreenshot)driver;
              File source=takescreenshot.getScreenshotAs(OutputType.FILE);
              FileUtils.copyFile(source, new File("./Screenshots/"+Screenshotname+".png"));
              System.out.println("Screenshot Taken Successfully!!!!");
             
       }

}


This class will just capture the screenshots by calling this Method in Test class

CaptureScreenshot.takescreenshot(driver, "Titlefailed");




      2. Create a new Class for the Test.

      3. On BeforeTest annotation Write code to  Open Browser and Navigate to http:\\automationplace.blogspot.com



@BeforeTest
       public void Setup()
       {
              driver=new FirefoxDriver();
              driver.manage().window().maximize();
              driver.get("http:\\automationplace.blogspot.com");
             
              //Make testcase fail by checking the Title
             
       }


       4. On the @Test annotation, Just verify the title (Here am forcefully failing the Testcase by giving wrong title on Expected String in Assert.equal method)


String ExpectedTitle="Automation";

 forcefully failing the Testcase by giving wrong title on the ExpectedTitle.

@Test
       public void verifytitle()
       {
              String ActualTitle=driver.getTitle();
              System.out.println(ActualTitle);
              //Removed "Place" string from Title to fail testcase
              Assert.assertEquals(ActualTitle, ExpectedTitle);
       }


     5. Capture ScreenShot on the @AfterMethod,

     Note :

1. We will use ITestResult Interface which will provide us the test case execution status and test case name.
2.@AfterMethod is another annotation of TestNG which will execute after evert test execution whether test case pass or fail @AfterMethod will always execute.

@AfterMethod
       public void TearDown(ITestResult result) throws IOException
       {
              //If the Testcase fail then only it enters to if condition block
             
              //.getStatus will return Test "Pass" or "Fail"
             
              System.out.println("Testcase status is"+result.getStatus());
              System.out.println("Iresult status is"+result.FAILURE);
             
              if(result.FAILURE == result.getStatus())
              {
                     //Now we need to capture Screenshot
                     //use CaptureScreenshot Class to Take Screenshot
                    
                     CaptureScreenshot.takescreenshot(driver, "Titlefailed");
                    
              }
             
             
              driver.quit();
       }


1.If the Testcase fail then only it enters to if condition block

2.getStatus will return Test "Pass" or "Fail"




It will Store ScreenShot on the Project folder like this








Source Code: 


Class to take ScreenShot:  CreateScreenShot.java

import java.io.File;
import java.io.IOException;

import javax.print.attribute.standard.MediaSize.Other;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;


public class CaptureScreenshot {
      
       public static void takescreenshot(WebDriver driver,String Screenshotname) throws IOException
       {
              TakesScreenshot takescreenshot=(TakesScreenshot)driver;
              File source=takescreenshot.getScreenshotAs(OutputType.FILE);
              FileUtils.copyFile(source, new File("./Screenshots/"+Screenshotname+".png"));
              System.out.println("Screenshot Taken Successfully!!!!");
             
       }

}



Class for the Testcase :FailedTestCase.java

import java.io.IOException;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.ITestResult;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;


public class FailedTestcase {
      
       WebDriver driver;
       String ExpectedTitle="Automation";
      
       @BeforeTest
       public void Setup()
       {
              driver=new FirefoxDriver();
              driver.manage().window().maximize();
              driver.get("http:\\automationplace.blogspot.com");
             
              //Make testcase fail by checking the Title
             
       }
      
       //Failed Testcase
       @Test
       public void verifytitle()
       {
              String ActualTitle=driver.getTitle();
              System.out.println(ActualTitle);
              //Removed "Place" string from Title to fail testcase
              Assert.assertEquals(ActualTitle, ExpectedTitle);
       }
      
      
       @AfterMethod
       public void TearDown(ITestResult result) throws IOException
       {
              //If the Testcase fail then only it enters to if condition block
             
              //.getStatus will return Test "Pass" or "Fail"
             
              System.out.println("Testcase status is"+result.getStatus());
              System.out.println("Iresult status is"+result.FAILURE);
             
              if(result.FAILURE == result.getStatus())
              {
                     //Now we need to capture Screenshot
                     //use CaptureScreenshot Class to Take Screenshot
                    
                     CaptureScreenshot.takescreenshot(driver, "Titlefailed");
                    
              }
             
             
              driver.quit();
       }
      


}


Run the program .

You find the Screenshot on the project folder after Execution.







Thats it..Have a great day.

Thankyou!!!!





20 comments:

  1. How can i attach the screen shot to my testNg index.html report using Reporter.log() ? Pls help.

    ReplyDelete
  2. How can i attach the screen shot to my testNg index.html report using Reporter.log() ? Pls help.

    ReplyDelete
  3. Good ans simple solution. Used for my Appium project

    ReplyDelete
  4. vmware workstation 11 to buy , windows 10 enterprise key , windows 10 activation i , windows 10 product key after upgrade , windows 10 activation commands , windows 10 10240 serial key , windows anytime upgrade key , windows home server product key download , t3PEmK

    office 2016 product serial free

    windows 10 enterprise key

    office 2016 product key

    Windows 10 product key code sale

    ReplyDelete
  5. Hi All,

    I was unable to take the screenshot, here is the screenshot.

    FAILED CONFIGURATION: @AfterMethod TearDown([TestResult name=TC_5 status=FAILURE method=WithoutGrid_MSPrice_Roundtrip.TC_5()[pri:5, instance:Withoutgrid.WithoutGrid_MSPrice_Roundtrip@2f686d1f] output={null}])
    java.io.IOException: The device is not ready
    at java.io.WinNTFileSystem.canonicalize0(Native Method)
    at java.io.WinNTFileSystem.canonicalize(Unknown Source)
    at java.io.File.getCanonicalPath(Unknown Source)
    at org.apache.commons.io.FileUtils.copyFile(FileUtils.java:1079)
    at org.apache.commons.io.FileUtils.copyFile(FileUtils.java:1038)
    at Withoutgrid.CaptureScreenshot.takescreenshot(CaptureScreenshot.java:30)
    at Withoutgrid.WithoutGrid_MSPrice_Roundtrip.TearDown(WithoutGrid_MSPrice_Roundtrip.java:278)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:85)
    at org.testng.internal.Invoker.invokeConfigurationMethod(Invoker.java:510)
    at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:211)
    at org.testng.internal.Invoker.invokeMethod(Invoker.java:703)
    at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:816)
    at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1124)
    at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:125)
    at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:108)
    at org.testng.TestRunner.privateRun(TestRunner.java:774)
    at org.testng.TestRunner.run(TestRunner.java:624)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:359)
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:354)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:312)
    at org.testng.SuiteRunner.run(SuiteRunner.java:261)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1215)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1140)
    at org.testng.TestNG.run(TestNG.java:1048)
    at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:132)
    at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:236)
    at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:81)

    ReplyDelete
  6. I appreciate your efforts because it conveys the message of what you are trying to say. It's a great skill to make even the person who doesn't know about the subject could able to understand the subject . Your blogs are understandable and also elaborately described. I hope to read more and more interesting articles from your blog. All the best.


    rpa Training in annanagar

    blue prism Training in annanagar

    automation anywhere Training in annanagar

    iot Training in annanagar

    rpa Training in marathahalli

    blue prism Training in marathahalli

    automation anywhere Training in marathahalli

    blue prism training in jayanagar

    automation anywhere training in jayanagar

    ReplyDelete
  7. It's interesting that many of the bloggers to helped clarify a few things for me as well as giving.Most of ideas can be nice content.The people to give them a good shake to get your point and across the command
    python training in rajajinagar
    Python training in btm
    Python training in usa
    Python training in marathahalli
    Python training in pune

    ReplyDelete
  8. Really great post, I simply unearthed your site and needed to say that I have truly appreciated perusing your blog entries.
    Blueprism online training

    Blue Prism Training in Pune

    ReplyDelete
  9. Your new valuable key points imply much a person like me and extremely more to my office workers.With thanks; from every one of us.
    apple service center chennai | Mac service center in chennai | ipod service center in chennai | Apple laptop service center in chennai

    ReplyDelete
  10. This comment has been removed by the author.

    ReplyDelete
  11. I like the helpful info you supply in your articles. I’ll bookmark your weblog and take a look at once more here regularly. I am relatively certain I will learn a lot of new stuff right here! Good luck for the following!
    angular js training in chennai

    angular js training in velachery

    full stack training in chennai

    full stack training in velachery

    php training in chennai

    php training in velachery

    photoshop training in chennai

    photoshop training in velachery

    ReplyDelete