博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[Selenium+Java] Listeners and their use in Selenium WebDriver
阅读量:4509 次
发布时间:2019-06-08

本文共 8848 字,大约阅读时间需要 29 分钟。

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 onListeners. 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 thereports.

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 "

  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

Loginstarted

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

你可能感兴趣的文章
微信小程序——获取步数
查看>>
代理原有的Handler.Callback,感知Application onCreate的结束时间
查看>>
Delphi 皮肤控件AlphaControls的使用
查看>>
pycharm快捷键大全
查看>>
Smarty 简单使用
查看>>
冒泡排序
查看>>
30分钟泛型教程
查看>>
信息与信息工具的意义
查看>>
Http 状态码:
查看>>
js 对象操作赋值操作
查看>>
关于IE6的一些需求分析
查看>>
【IPv6】ISATAP隧道技术详解
查看>>
numpy_pandas
查看>>
oracle数据导入/导出(2)
查看>>
SSH远程会话管理工具 - screen使用教程
查看>>
设计模式
查看>>
前端复习-01-dom操作包括ie和现代浏览器处理相关
查看>>
[CF612D] The Union of k-Segments(排序,扫描线)
查看>>
linux安装nginx
查看>>
spark书籍视频推荐
查看>>