Everything you need to know about the Listeners in Selenium

Last updated on Sep 10,2024 14.3K Views

Everything you need to know about the Listeners in Selenium

edureka.co

When you are using multiple functions in Java, you might have to pass data from one function to another. Similarly, when you are trying to test multiple web pages, you might have to pass data from one web page to another. Selenium provides various functionalities to interact with the web pages. One such interaction is done using Listeners.

So, let’s begin by learning about what are listeners in Selenium,

Listeners in Selenium: What are listeners?

Let me put it across like this. Listeners are basically the ones who have the ability to listen to a particular event. It is defined as an interface that modifies the behavior of the system. Listeners allow customization of reports and logs.

To get a better idea about how listeners work in Selenium, we need to understand its major types. So, let’s see what are different types of listeners in the next topic.

Listeners in Selenium: Types of listeners

Listeners mainly comprise of two types, namely
  1. WebDriver listeners
  2. TestNG listeners

So, first, let’s understand what are WebDriver listeners. 

Types of listeners: WebDriver listeners

WebDriverEventListener interface allows to implement  methods and classes like WebDriverEventListener and EventFiringWebDriver. 

Let’s understand it in detail

WebDriverEventListener

Let’s see how to implement Listeners in Selenium WebDriver Script.

Step 1: Create a Class “EventCapture” to implement the WebDriverEventListener methods


package listeners;

public class EventCapture{

}

package listeners;

public class EventCapture implements WebDriverEventListener{

}

Step 2: Create another Class “ListenerMainClass” and write a script 

Step 3: Create EventFiringWebDriver object in the Class “ListenerMainClass“, and pass driver object as a parameter

 EventFiringWebDriver eventHandler = new EventFiringWebDriver(driver); 

Step 4: Under the “ListenerMainClass“, Create an object of the Class “EventCapture” to implement all the methods of WebDriverEventListener to register with the EventFiringWebDriver

EventCapture eCapture = new EventCapture();

Now let’s see how we can implement the WebDriver event listeners.

In this case, we’ll try automating our official web page “edureka.co” to understand how WebDriver event listeners work


import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.events.WebDriverEventListener;
//WebDriver Event Listeners
public class EventCapture implements WebDriverEventListener{
 
 
 public void afterChangeValueOf(WebElement arg0, WebDriver arg1) {
 // TODO Auto-generated method stub
 
 }
 
 @Override
 public void afterClickOn(WebElement arg0, WebDriver arg1) {
 // TODO Auto-generated method stub
 
 }
 
 @Override
 public void afterFindBy(By arg0, WebElement arg1, WebDriver arg2) {
 // TODO Auto-generated method stub
 
 }
 
 @Override
 public void afterNavigateBack(WebDriver arg0) {
 // TODO Auto-generated method stub
 
 }
 
 @Override
 public void afterNavigateForward(WebDriver arg0) {
 // TODO Auto-generated method stub
 
 }
 
 @Override
 public void afterNavigateTo(String arg0, WebDriver arg1) {
 // TODO Auto-generated method stub
 
 }
 
 public void beforeChangeValueOf(WebElement arg0, WebDriver arg1) {
 // TODO Auto-generated method stub
 
 }
 
 @Override
 public void beforeClickOn(WebElement arg0, WebDriver arg1) {
 // TODO Auto-generated method stub
 
 }
 
 @Override
 public void beforeFindBy(By arg0, WebElement arg1, WebDriver arg2) {
 // TODO Auto-generated method stub
 
 }
 
 @Override
 public void beforeNavigateBack(WebDriver arg0) {
 // TODO Auto-generated method stub
 
 }
 
 @Override
 public void beforeNavigateForward(WebDriver arg0) {
 // TODO Auto-generated method stub
 
 }
 
 @Override
 public void beforeNavigateRefresh(WebDriver arg0) {
 // TODO Auto-generated method stub
 
 }
 
 @Override
 public void beforeNavigateTo(String arg0, WebDriver arg1) {
 // TODO Auto-generated method stub
 
 }
 
 @Override
 public void onException(Throwable arg0, WebDriver arg1) {
 // TODO Auto-generated method stub
 
 }

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

@Override
public void afterChangeValueOf(WebElement arg0, WebDriver arg1, CharSequence[] arg2) {
	// TODO Auto-generated method stub
	
}

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

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

@Override
public void beforeChangeValueOf(WebElement arg0, WebDriver arg1, CharSequence[] arg2) {
	// TODO Auto-generated method stub
	
}

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

@Override
public void beforeScript(String arg0, WebDriver arg1) {
	// TODO Auto-generated method stub
	
}

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

@Override
public void afterScript(String arg0, WebDriver arg1) {
	// TODO Auto-generated method stub
	
} 
 
}

Once this is done, we need a main class to perform actions on the methods declared in the EventCapture program.


import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.events.EventFiringWebDriver;

public class ListenerMainClass {

public static void main (String [] args) throws InterruptedException{
System.setProperty("webdriver.chrome.driver", "C:UsersVaishnaviDesktopChromechromedriver.exe");
WebDriver driver = new ChromeDriver();
JavascriptExecutor js = (JavascriptExecutor)driver;
EventFiringWebDriver eventHandler = new EventFiringWebDriver(driver);
EventCapture eCapture = new EventCapture();
//Registering with EventFiringWebDriver
//Register method allows to register our implementation of WebDriverEventListner to listen to the WebDriver events
eventHandler.register(eCapture);
//navigating to the webpage "www.edureka.co"
eventHandler.navigate().to("https://www.edureka.co/blog/");
js.executeScript("window.scrollBy(0,400)");
Thread.sleep(3000);
eventHandler.findElement(By.linkText("Software Testing")).click();
//navigating to the webpage "www.edureka.co/all-courses/"
eventHandler.navigate().to("https://www.edureka.co/all-courses");
//navigating back to the first page
eventHandler.navigate().back();
eventHandler.quit();
//Unregister allows to detach
eventHandler.unregister(eCapture);
System.out.println("End of Listners Class");
}
}

Learn more about testing methodologies and their concepts from the Software testing course for beginners.

Now let’s see what is the output of this program.

First, it’ll navigate to the web page www.edureka.co/blog

Next, scrolls down the page

Then searches for Software testing link and clicks on the link

After this, pause the execution for a few seconds and navigate back to the previous web page

This is everything you need to know about the WebDriver listeners

Now, let’s understand what happens in the TestNG listeners

TestNG Listeners

TestNG can be made to listen to what we say with the help of Listeners. Listeners give us the flexibility to alter the default TestNG behavior.

Now let’s understand a few functions that help in easy execution

ITestListener: This function first makes a call to onStart() method and runs the scripts. In a similar way, it again makes a call to onFinish() method after a suite finishes execution and it makes the call before and after the Test. It has seven methods in it.
OnStart: This method is called when the test starts.
OnTestSuccess: This method is called on the success of any test.
onTestFailure: This method is called on the failure of any test.
onTestSkipped: This method is called when the test is skipped
onTestFailedButWithinSuccessPercentage: This method is called each time test fails but is within success percentage.
onFinish: This method is called after all the tests are executed.

Having understood this, let’s take a look at the implementation process

In this case, we’ll test our official website edureka.co

Step 1): Create class “ListenerTest” that implements ‘ITestListener’. Add the corresponding methods like OnStart(), OnTestSuccess() and so on

Step 2): Create another class “TestCases” for the process automation. Selenium will execute this ‘TestCases’ to successfully run the test scripts.

Step 3): Next, implement this listener in the regular class i.e. “TestCases”. There is a way to connect to the class and interface. It is by using the listeners annotations.


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 4): Execute the “TestCases” class. All the methods in the class “ListenerTest” are called automatically based on their behavior and the methods annotated as @Test.

[java]
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;

@Listeners(ListenerTest.class)

public class TestCases {
public WebDriver driver;

//Test to pass as to verify listeners.
@Test
public void Login() throws Exception
{
System.setProperty("webdriver.chrome.driver", "C:UsersVaishnaviDownloadschromedriver_win32 (2)chromedriver.exe");
driver = new ChromeDriver();
driver.get("https://www.edureka.co/");
JavascriptExecutor js = (JavascriptExecutor) driver;
driver.manage().window().maximize();
driver.findElement(By.cssSelector("#search-inp")).sendKeys("Test Automation Engineer Masters Program");
driver.findElement(By.className("typeahead__button")).click();
js.executeScript("window.scrollBy(0,500)");
Thread.sleep(3000);
js.executeScript("window.scrollBy(0,700)");
Thread.sleep(4000);
js.executeScript("window.scrollBy(0,700)");
Thread.sleep(4000);
}

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

Step 5): Verify the Output.

First, it will get the URL of the web page

Finds the search box and sends the text

It fails to click the search icon. Scrolls down the web page

Listeners In Selenium | How To Implement testNG Listeners In Selenium | Edureka

This video on ‘Listeners in Selenium’ helps you understand how Selenium provides functionalities that help in listening to any event that is carried out on the webpage.

Now let’s move on to our final topic, which is, what are the major differences between the WebDriver listener and the TestNG listener

Difference between WebDriver and TestNG listeners

 

 
TestNG ListenersWebDriver Listeners
Used to generate the report for tests. Helps in capturing screenshots. Performs jobs like TestNG listeners like logging in and reporting but works on different events

Now with this, we come to an end to this “Listeners in Selenium” blog. I Hope you guys enjoyed this article and understood what Listeners are in Selenium.

For details, You can even check out test automation strategies and methodology concepts with the QA Automation course.

Now that you have understood how TestNG listeners and WebDriver listeners work in Selenium, check out the Selenium Certification Course by Edureka, a trusted online learning company with a network of more than 650,000 satisfied learners spread across the globe. This course is designed to introduce you to the complete Selenium features and its importance in testing software. Got a question for us? Please mention it in the comments section of “Listeners in Selenium” and we will get back to you.

Find out our Selenium Training in Top Cities/Countries

IndiaOther Cities/Countries
BangaloreUS
HyderabadUK
PuneCanada
ChennaiAustralia
MumbaiSingapore
KolkataEdinburgh

Upcoming Batches For Selenium Course
Course NameDateDetails
Selenium Course

Class Starts on 23rd November,2024

23rd November

SAT&SUN (Weekend Batch)
View Details
Selenium Course

Class Starts on 25th November,2024

25th November

MON-FRI (Weekday Batch)
View Details
Selenium Course

Class Starts on 21st December,2024

21st December

SAT&SUN (Weekend Batch)
View Details
BROWSE COURSES
REGISTER FOR FREE WEBINAR Selenium Framework Explained in 60 Minutes