Everything you need to know about the Listeners in Selenium
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, folks, through the medium of this article, I will discuss everything you need to know about Listeners in Selenium.
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
- WebDriver listeners
- 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
-This is an interface which holds some predefined methods. These Webdriver events are helpful to view the events triggered by the webdriver.
-It plays an important role in analyzing the results and helps us in debugging issues if we encounter any.
-It has ability to track different events like “beforeNavigateTo” , “afterNavigateTo”, “BeforeClickOn”, “AfterClickOn” and many more.
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
- First, create a class EventCapture which implements the WebDriverEventListener.
- Add different methods which help in easy execution.
- afterChangeValueOf() method is called every time when you want to return the value of the element after it is been changed or modified
- Override the methods which help in invoking of functions from the base class in the derived class.
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.
- Instantiate the WebDriver instance with the browser driver, ChromeDriver
- Create an object of the EventFiringWebDriver and call it eventHandler
- Declare the JavaScriptExecutor which acts as an interface while executing the selenium script
- Create an object of the EventCapture eCapture and register the event
- Get the URL of the web page: eventHandler.navigate().to(“https://www.edureka.co/blog/”);
- Perform actions on the web page like scrolling, using the JavaScriptExecutor
- Find the element on the web page using the element locator, the LinkText
- Use the object of the EventFiringWebDriver to navigate to a new page: eventHandler.navigate().to(“https://www.edureka.co/all-courses”);
- Then navigate back to the first page
- Quit the driver execution using this command eventHandler.quit();
- Unregister the object of the EventCapture, eCapture
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");
}
}
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.
- TestNG listener is formally called as ITestListener, which is an interface in TestNG.
- A normal Java class implements ITestListener and overrides all the corresponding methods written inside it.
- Each method sums up to an event of the respective Selenium Project
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
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
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.