Sample TestNG suite file with Custom Listener
Sample TestNG suite file with Custom Listener
In this post, we will go through a sample TestNG suite file with Custom Listener. Also, we will discuss a sample test method that opens the Firefox browser and searches the Bing search engine.
A Simple TestNG suite file
Maven TestNG dependency: Add this to pom.xml
<!-- TestNG Maven dependency --> <dependency> <groupId>org.testng</groupId> <artifactId>testng</artifactId> <version>6.9.10</version> </dependency>
Sample TestNG suite file below :
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd"> <suite name="BingSuite" verbose="0"> <test name="FirefoxBingTest"> <parameter name="browser" value="firefox" /> <classes> <class name="com.testingdocs.sample.selenium.framework.scripts.Search_Bing" /> </classes> </test> <listeners> <listener class-name="com.testingdocs.sample.selenium.extras.MyTestListener"> </listener> </listeners> </suite>
Reading parameters from testng.xml file : TestNG : Reading Parameters from testng.xml
Sample TestNG @Test method below:
@Test public void Bing_Search_Test() throws Exception { FirefoxDriver driver = new FirefoxDriver(); driver.get("https://www.bing.com/"); WebElement element = driver.findElement(By.id("sb_form_q")); element.sendKeys("Hello Bing!"); driver.findElement(By.id("sb_form_go")).click(); WebDriverWait wait = new WebDriverWait(driver, 120); wait.until(ExpectedConditions.titleContains("Hello")); Assert.assertEquals("Hello - Bing", driver.getTitle()); }
The class in the suite file “com.testingdocs.sample.selenium.framework.scripts.Search_Bing” has a @Test method. Also, it will search Microsoft Bing on the Mozilla Firefox browser and verify the search results Title on the Bing search web page.
The @Test method opens Bing page in Mozilla Firefox browser :
FirefoxDriver driver = new FirefoxDriver(); driver.get("https://www.bing.com/");
Enter “Hello Bing!” into the search text area web element :
WebElement element = driver.findElement(By.id("sb_form_q")); element.sendKeys("Hello Bing!");
The program then clicks search and waits for 2 minutes.
driver.findElement(By.id("sb_form_go")).click(); WebDriverWait wait = new WebDriverWait(driver, 120); wait.until(ExpectedConditions.titleContains("Hello"));
Then checks the title of the window.
Assert.assertEquals("Hello Bing! - Bing", driver.getTitle());
You have run your first TestNG program and test..!!
The suite file has a custom listener that listens to the test run and reports pass/fail.( We will talk about this in details later ) .TestNG has a default listener to listen to tests.The TestNG sample listener “com.testingdocs.sample.selenium.extras.MyTestListener” listens to the tests in this example.
We can use customer listeners in the TestNG framework to override the default behavior of the framework on conditions like test success, failure, skip conditions, etc.