[Selenium+java] Listeners and their use in Selenium webdriver

Source: Internet
Author: User
Tags assert stub testng guru99



Original URL: https://www.guru99.com/listeners-selenium-webdriver.html


TestNG Listeners in Selenium webdriver


There is the main listeners.


    1. Webdriver Listeners
    2. TestNG Listeners


In this tutorial, we'll discuss on Testng Listeners. Here's what you'll learn-


    • What's Listeners in Selenium webdriver?

    • Types of Listeners in TestNG

    • Test Scenario:

    • Steps to create a TestNG Listener

    • Use of Listener for multiple classes.

What's Listeners in Selenium webdriver?


Listener is defined as interface that modifes the default TestNG ' s behavior. As the name suggests Listeners "Listen" to the event defined in the selenium script and behave accordingly. It is used in selenium by implementing Listeners Interface. It allows customizing TestNG reports or logs. There is many types of TestNG listeners available.





Types of Listeners in TestNG


There is many types of listeners which allows the TestNG ' s behavior.



Below is the few TestNG listeners:


    1. Iannotationtransformer,
    2. IAnnotationTransformer2,
    3. Iconfigurable,
    4. Iconfigurationlistener,
    5. Iexecutionlistener,
    6. Ihookable,
    7. Iinvokedmethodlistener,
    8. IInvokedMethodListener2,
    9. Imethodinterceptor,
    10. ireporter,
    11. Isuitelistener,
    12. Itestlistener.


Above Interface is called TestNG Listeners. These interfaces is used in selenium to generate logs or customize the testing reports.



In this tutorial, we'll implement the Itestlistener.



Itestlistener has following methods


    • onstart- OnStart method is called if any Test starts.
    • ontestsuccess- ontestsuccess method is called on the success of any Test.
    • ontestfailure- Ontestfailure method is called on the failure of any Test.
    • ontestskipped- ontestskipped method is called on skipped of any Test.
    • ontestfailedbutwithinsuccesspercentage- method is called each time Test fails and is within success percentage.
    • onfinish- OnFinish method is called after all Tests be executed.
Test Scenario:


In this test scenario, we'll automate Login process and implement the ' Itestlistener '.


    1. Launch the Firefox and open the site "http://demo.guru99.com/V4/"




    1. Login to the application.




Steps to create a TestNG Listener


For the above test scenario, we'll implement Listener.



Step 1) Create class "Listener_demo" and Implements ' Itestlistener '. Move the mouse over redline text, and Eclipse would suggest you 2 quick fixes as shown on below screen:






Just click on "Add unimplemented methods". Multiple unimplemented methods (without a body) is added to the code. Check below-


package Listener_Demo;		

import org.testng.ITestContext ;		
import org.testng.ITestListener ;		
import org.testng.ITestResult ;		

public class ListenerTest implements ITestListener						
{		

    @Override		
    public void onFinish(ITestContext arg0) {					
        // TODO Auto-generated method stub				
        		
    }		

    @Override		
    public void onStart(ITestContext arg0) {					
        // TODO Auto-generated method stub				
        		
    }		

    @Override		
    public void onTestFailedButWithinSuccessPercentage(ITestResult arg0) {					
        // TODO Auto-generated method stub				
        		
    }		

    @Override		
    public void onTestFailure(ITestResult arg0) {					
        // TODO Auto-generated method stub				
        		
    }		

    @Override		
    public void onTestSkipped(ITestResult arg0) {					
        // TODO Auto-generated method stub				
        		
    }		

    @Override		
    public void onTestStart(ITestResult arg0) {					
        // TODO Auto-generated method stub				
        		
    }		

    @Override		
    public void onTestSuccess(ITestResult arg0) {					
        // TODO Auto-generated method stub				
        		
    }		
}		


Let ' s modify the ' Listenertest ' class. In particular, we'll modify following methods-



Ontestfailure, ontestskipped, Onteststart, ontestsuccess, etc.



The modification is simple. We just print the name of the Test.



Logs is created in the console. It is easy for the user to understand which test is a pass, fail, and skip status.



After modification, the code looks like-


package Listener_Demo;		

import org.testng.ITestContext;		
import org.testng.ITestListener;		
import org.testng.ITestResult;		

public class ListenerTest implements ITestListener						
{		

    @Override		
    public void onFinish(ITestContext Result) 					
    {		
                		
    }		

    @Override		
    public void onStart(ITestContext Result)					
    {		
            		
    }		

    @Override		
    public void onTestFailedButWithinSuccessPercentage(ITestResult Result)					
    {		
    		
    }		

    // When Test case get failed, this method is called.		
    @Override		
    public void onTestFailure(ITestResult Result) 					
    {		
    System.out.println("The name of the testcase failed is :"+Result.getName());					
    }		

    // When Test case get Skipped, this method is called.		
    @Override		
    public void onTestSkipped(ITestResult Result)					
    {		
    System.out.println("The name of the testcase Skipped is :"+Result.getName());					
    }		

    // When Test case get Started, this method is called.		
    @Override		
    public void onTestStart(ITestResult Result)					
    {		
    System.out.println(Result.getName()+" test case started");					
    }		

    // When Test case get passed, this method is called.		
    @Override		
    public void onTestSuccess(ITestResult Result)					
    {		
    System.out.println("The name of the testcase passed is :"+Result.getName());					
    }		

}			


Step 2) Create another class "testcases" for the login process automation. Selenium'll execute this ' testcases ' to login automatically.


package Listener_Demo;		

import org.openqa.selenium.By;		
import org.openqa.selenium.WebDriver;		
import org.openqa.selenium.firefox.FirefoxDriver;		
import org.testng.Assert;		
import org.testng.annotations.Listeners;		
Import org.testng.annotations.Test;		

public class TestCases {				
WebDriver driver= new FirefoxDriver();					

// Test to pass as to verify listeners .		
@Test		
public void Login()				
{		
    driver.get("http://demo.guru99.com/V4/");					
    driver.findElement(By.name("uid")).sendKeys("mngr34926");							
    driver.findElement(By.name("password")).sendKeys("amUpenu");							
    driver.findElement(By.name("btnLogin")).click();					
}		

// Forcefully failed this test as to verify listener.		
@Test		
public void TestToFail()				
{		
    System.out.println("This method to test fail");					
    Assert.assertTrue(false);			
}		
}


Step 3) Next, implement this listener with our regular project class i.e. "Testcases". There is different ways to connect to the class and interface.



The first-is-to-use Listeners annotation (@Listeners) as shown below:


@Listeners (Listener_Demo.ListenerTest.class)


We Use this in the class "Testcases" as shown below.



So-Finally the class "Testcases" looks like after using Listener annotation:


package Listener_Demo;		

import org.openqa.selenium.By;		
import org.openqa.selenium.WebDriver;		
import org.openqa.selenium.firefox.FirefoxDriver;		
import org.testng.Assert;		
import org.testng.annotations.Listeners;		
import org.testng.annotations.Test;             		

@Listeners(Listener_Demo.ListenerTest.class)			

public class TestCases {				
WebDriver driver= new FirefoxDriver();					

//Test to pass as to verify listeners.		
@Test		
public void Login()				
{		
    driver.get("http://demo.guru99.com/V4/");					
    driver.findElement(By.name("uid")).sendKeys("mngr34926");							
    driver.findElement(By.name("password")).sendKeys("amUpenu");							
    driver.findElement(By.id("")).click();					
}		

//Forcefully failed this test as verify listener.		
@Test		
public void TestToFail()				
{		
    System.out.println("This method to test fail");					
    Assert.assertTrue(false);			
}		
}			


The project structure looks like:






Step 4): Execute the "Testcases" class. Methods in class "Listenertest" is called automatically according to the behavior of Methods annotated as @Test.



Step 5): Verify The Output that logs displays at the console.



Output of the ' testcases ' would look like this:






[TestNG] Running:



C:\Users\gauravn\AppData\Local\Temp\testng-eclipse--1058076918\testng-customsuite.xml



Login Test Case started



The name of the testcase passed Is:login



Testtofail Test Case started



This method to test fail



The name of the testcase failed Is:testtofail



Passed:login



Failed:testtofail



java.lang.AssertionError:expected [true] but found [false]


Use of Listener for multiple classes.


IF Project has multiple classes adding Listeners to each one of the them could be cumbersome and error prone.



In the such cases, we can create a testng.xml and add listeners tag in XML.






This listener are implemented throughout the test suite irrespective of the number of classes you have. When you run the this XML file, listeners'll work on the all classes mentioned. You can also declare any number of listener class.



Summary:



Listeners is required to generate logs or customize TestNG reports in Selenium Webdriver.


    • There is many types of listeners and can be used as per requirements.
    • Listeners is interfaces used in selenium Web driver script
    • Demonstrated the use of Listener in Selenium
    • Implemented the Listeners for multiple classes


[Selenium+java] Listeners and their use in Selenium webdriver


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.