[Selenium+Java] Listeners and their use in Selenium WebDriver

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

TestNG Listeners in Selenium WebDriver

There are two main listeners.

  1. WebDriver Listeners
  2. TestNG Listeners

In this tutorial, we will discuss onTestngListeners. Here is what you will learn-

What is 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 are many types of TestNG listeners available.

Types of Listeners in TestNG

There are many types of listeners which allows you to change the TestNG‘s behavior.

Below are 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 are called TestNG Listeners. These interfaces are used in selenium to generate logs or customize theTestingreports.

In this tutorial, we will implement the ITestListener.

ITestListener has following methods

  • OnStart- OnStart method is called when 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 but is within success percentage.
  • onFinish- onFinish method is called after all Tests are executed.

Test Scenario:

In this test scenario, we will 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 will implement Listener.

Step 1) Create class "Listener_Demo" and implements ‘ITestListener ‘. Move the mouse over redline text, and Eclipse will suggest you 2 quick fixes as shown in 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 will modify following methods-

onTestFailure, onTestSkipped, onTestStart, onTestSuccess, etc.

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

Logs are 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 will 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 in our regular project class i.e. "TestCases". There are two different ways to connect to the class and interface.

The first way 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 " are 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‘ will look like this:

[TestNG] Running:

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

LoginTest Casestarted

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 them could be cumbersome and error prone.

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

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

Summary:

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

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

原文地址:https://www.cnblogs.com/alicegu2009/p/9098706.html

时间: 2024-10-11 09:46:44

[Selenium+Java] Listeners and their use in Selenium WebDriver的相关文章

[Selenium+Java] Implicit Wait & Explicit Wait in Selenium

https://www.guru99.com/handling-dynamic-selenium-webdriver.html here are two types of HTML tables published on the web- Static tables: Data is static i.e. Number of rows and columns are fixed. Dynamic tables: Data is dynamic i.e. Number of rows and c

[Selenium+Java] Parallel Execution & Session Handling in Selenium

Source URL: https://www.guru99.com/sessions-parallel-run-and-dependency-in-selenium.html To understand how to run scripts in parallel, let's first understand Why do we need Session Handling? During test execution, the Selenium WebDriver has to intera

Selenium+Java 环境搭建

从事开发工作一年,测试工作三年,一直希望能够做自动化方面的测试,但因为各种缘由一直没做成,终于有时间自己学学.因为有一些java基础,所以从Selenium+Java开始. 搭建Selenium+Java环境过程发生很多问题,主要是浏览器版本和selenium jar包不兼容问题,在此做个总结. 先把所有需要的文件准备好: 1.jdk,可以直接官网下载,我这里是1.7  链接:http://pan.baidu.com/s/1dDDdAcp 密码:mt98 2.eclipse,可以直接官网下载  

Selenium+Java+Eclipse 自动化测试环境搭建

一.下载Java windows java下载链接 https://www.java.com/zh_CN/download/win10.jsp 二.安装Java 安装好后检查一下需不需要配置环境变量,现在java 8已经不用配置环境变量了,直接在命令行输入:java -version 三.下载和安装Eclipse windows Eclipse下载链接 https://www.eclipse.org/downloads/ 你也可以下载绿色版 四.下载selenium,然后解压 selenium

软件测试之Selenium Java WebDriver

编写Selenium Java WebDriver程序,测试inputgit.csv表格中的学号和git地址的对应关系 package selenium2; import java.util.regex.Pattern; import java.util.concurrent.TimeUnit; import org.junit.*; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import o

自动化测试框架selenium+java+TestNG——配置篇

最近来总结下自动化测试 selenium的一些常用框架测试搭配,由简入繁,最简单的就是selenium+java+TestNG了,因为我用的是java,就只是总结下java了. TestNG在线安装: 打开Eclipse   Help ->Install New Software ,   然后Add   "http://beust.com/eclipse" 选择TestNG,finish下一步完成安装. 验证是否安装成功 File->new->other 导入sele

Selenium Java WebDriver 使用

一. Firefox安装Selenium插件 在FireFox的菜单中的附加组件中搜索Selenium IDE 然后安装 二. 使用Selenium IDE录制脚本/导出脚本 点击图中标志打开Selenium IDE 红色按钮按下表示正在录制,这时候只用将界面切换到Firefox,网址中输入www.baidu.com,然后再搜索框中输入文字,点击搜索,所有的控件的访问都会被记录下来,然后切换回seleniumIDE就可以看到已经录制完毕 然后在图中红色选中的区域可以调整重新执行的速度,蓝色选中区

selenium+java:获取列表中的值

selenium+java:获取列表中的值 (2011-08-23 17:14:48) 标签: 杂谈 分类: selenium 初步研究利用java+testNg框架下写selenium测试用例,今天学会了几个API:(1)获取页面上列表中的值,并打印输出:System.out.println(selenium.getTable("xpath=/html/body/div[3]/form/table.1.1")); //输出列表中第1行第1列的值(2)判断页面上是否有某个文本:(只能判

Selenium Web 自动化 - Selenium(Java)环境搭建

Selenium Web 自动化 - Selenium(Java)环境搭建 2016-07-29 第1章 Selenium环境搭建 1.1 下载JDK JDK下载地址:http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html 1.2 安装和配置JDK 安装目录尽量不要有空格  D:\Java\jdk1.8.0_91; D:\Java\jre8 设置环境变量: “我的电脑”->右键->“