TestingDocs.com
Software Testing website
  • JBehave
  • Selenium
  • Testlink
  • Maven
  • Git
  • RAPTOR
  • Questions

How to Take Screenshot with TestNG when an Assert fails

Tweet
Pin it

Document Contents

  • Introduction
  • Code Listing:
  • Sample tests code
  • Common mistakes
  • Test Listener

Introduction

Lets learn the steps involved to take screenshot in TestNG framework when an assert fails in test methods.

To get started, let’s use this article to demonstrate specifically customized screenshot capture features in the TestNG Automation framework. It’s an awesome capability is to capture a screenshot when an Assert fails with TestNG Framework. We can write custom assertions in TestNG by overriding the onAssertFailure() method in the Assert lifecycle. This capability hooks this method to capture the screen whenever an Assert Fails during the test runs.

TestNG Assert Lifecycle

https://www.testingdocs.com/testng-assert-lifecycle/

Code Listing:

public class CustomAssertion extends Assertion {

@Override
 public void onAssertFailure(IAssert<?> assertCommand, 
AssertionError ex) {
 // TakingScreen here
 File scrFile = ((TakesScreenshot) driver)
 .getScreenshotAs(OutputType.FILE);
 try {
 FileUtils.copyFile(scrFile, new File("AssertFailure_" + 
assertCommand.getMessage()+ ".jpg"));
 }
 catch (IOException e) {
 e.printStackTrace();
 }
 }
 }



 

We can instantiate the class and use it in the test classes code as shown:

Sample tests code

public class TakeScreenShotOnAssertFail {

      private CustomAssertion m_custom = new CustomAssertion();
      public static WebDriver driver ;
     
      @Test
      public void sampleTilteFailureTest()
      {
          System.setProperty("webdriver.edge.driver", 
"MicrosoftWebDriver.exe");
          driver=new EdgeDriver();
          driver.navigate().to("https://www.twitter.com");
          driver.manage().window().maximize();
          WebDriverWait wait = new WebDriverWait(driver, 120);
          wait.until(ExpectedConditions.titleContains("Twitter"));
          m_custom.assertEquals("Facebook", driver.getTitle(),
"AssertFacebookInsteadTwitter");
        
      }
     
      @Test
      public void samplePassTest(){
        m_custom.assertEquals("Facebook","Facebook" ,
"AssertPassNoScreenShotRequired");
      }
      
      @AfterClass
      public void close() {
        driver.quit();
          }

}

 

Feel free to modify the test code. You might even want to add your logic to the test code.

By running the above code, you can capture a screenshot of the failed assert. The screenshot filename will be created with the Assert message as shown in the above code snippet.

 

Assert fail Screenshot

Common mistakes

Wondering why the screenshots are not created when tests and assert fails. Below are some of the common pitfalls.

Use the updated TestNG framework. TestNG testing framework might also have defects. So make sure you are using the updated and latest version of the tool.

Remove deprecated code from your tests. Update your tests with the latest Selenium code.

Proper imports in the tests. Screenshot code needs Webdriver driver object and file handling utilities.

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.8.0</version>
</dependency>

Test exceptions like TimeOut, SocketException exceptions fail fast and do not make the assert validations.

The above code appends the Assert message to the screenshot file. This might fail if the assert message has some illegal character that is not allowed by the operating system filenames. The test will encounter InvalidPathException.

For example: if the assert message is Assert -> will fail.

 

Assert Failed Test Exception


sampleAssertFailureTest

java.nio.file.InvalidPathException: Illegal char <>> at index 23: 
AssertFailure_Assert1 -> will fail.jpg at 
java.base/sun.nio.fs.WindowsPathParser
.normalize(WindowsPathParser.java:182)
 at java.base/sun.nio.fs.WindowsPathParser
.parse(WindowsPathParser.java:153)
 at java.base/sun.nio.fs.WindowsPathParser
.parse(WindowsPathParser.java:77)
 at java.base/sun.nio.fs.WindowsPath
.parse(WindowsPath.java:92)
 at java.base/sun.nio.fs.WindowsFileSystem
.getPath(WindowsFileSystem.java:229)
 at java.base/java.io.File.toPath(File.java:2311)

Test Listener

We can mix this capability with Test listening to highlight web elements in the screenshots.

For more information:

https://www.testingdocs.com/eventfiringwebdriver/

https://www.testingdocs.com/questions/how-to-highlight-web-elements-on-the-page-in-selenium-tests/


 

Consider options for capabilities to capture every assert life cycle method. Try mixing the assert lifecycle hooks along with SoftAssert capability to listen to every assert in the @Test annotated method. You can now enhance these custom capabilities & hook them into the TestNG framework for enhanced, robust visual logging to the framework. In conclusion, we’ve created a powerful new capability to give greater control over the test runs.

 

TestNG Tutorials on this website can be found at:

https://www.testingdocs.com/testng-framework-tutorial/

For more details on the TestNG Framework, visit the official website of TestNG at:

https://testng.org

Related Posts

TestNG /

Running tests from TestNG Suite testng.xml file

TestNG /

Add the TestNG library to the project

TestNG /

Create TestNG test class in Eclipse IDE.

TestNG /

Enable TestNG in IntelliJ IDE

TestNG /

Installing TestNG latest version from the update site.

Tag Cloud

Agile Appium Tutorials C++ Eclipse Tutorials Git Tutorials IntelliJ Tutorials Java Java Tutorial JBehave Jenkins Jira Cloud JUnit Tutorial Maven Object-oriented Flowchart Python Tutorials Raptor Flowcharts Selenium IDE TestLink Tutorials

Random Posts

  • TestLink Bitnami Cloud Image
    Overview In this tutorial, we will see the steps

    Read more

  • Code Coverage Tools
    Overview Let’s look at some of the code coverage

    Read more

  • pCloudy Continuous Testing Cloud
    Overview pCloudy is a continuous testing cloud

    Read more

Latest Tweets

Tweets by @TestingDocs

Back to Top

TestingDocs.com

  • Privacy Policy
  • Cookie Policy
  • JBehave
  • Selenium
  • Testlink
  • Maven
  • Git
  • RAPTOR
  • Questions
www.TestingDocs.com | All Rights Reserved