Thursday, January 1, 2015

Listners in Testng Framework



  1.  @listner is a testNG annotation

·         This is one very important annotation if you chose to have some default behavior for your test case when it failspasses and skip etc.

·         2. You can either extend 'TestListenerAdapter' or implement Interface 'ITestListener' which is a listener for test running.

              Eg : if you extend TestListenerAdapter class and write your implementation in a custom listner  to override onTestFailure or onTestSuccess methods you will be able to do  anything which you want when a test fails or passes, like taking screenshots,printing logs etc.

i.e)  Suppose your test case is passed and you want to write something in console at that case just you need to override a method onTestSuccess(ITestResult tr)
      Suppose your test case is failed and you want to take screenshot at that case just you need to override a method onTestFailure(ITestResult tr)

Methods available in TestListnerAdapter

·       1.  OnTestSuccess : Invoked each time a test succeeds.
·       2.  OnTestFailure : Invoked each time a test fails
We can implement any logic that you want to do when a test fails, Normally most of them prefer 
taking screen shots when a test fails. Here in this method we can add a logic to take the screen shot and the name of the test as screenshot name.
·         OnTestSkipped : Invoked each time a test is skipped.



In this program :
  1. Navigating to gmail
      driver.get("http://www.gmail.com"); 

   2. Verifying the Heading 

   Assert.assertEquals(Heading, "One account. All of Google.");

   3. Failing the testcase because there is no signin webelement

     driver.findElement(By.name("signin")).click();



In listnerclass.java:

   1. For Passed test am just printing like "Test Passed" in console

   public void onTestSuccess(ITestResult tr)  {
               
                System.out.println("TestPassed");
               }
      
   2 . For Failed Test am taking Screenshot and store it in (D:\\failure.png) drive


      public void onTestFailure(ITestResult itr)
       {
             
             
              File scrFile = ((TakesScreenshot)Properties.driver).getScreenshotAs(OutputType.FILE);
              // Now you can do whatever you need to do with it, for example copy somewhere
              try {
                     FileUtils.copyFile(scrFilenew File("D:\\failure.png"));
              } catch (IOException e) {
                     // TODO Auto-generated catch block
                     e.printStackTrace();
              }
              System.out.println("Taken screenshot because testcase failed");
             
       }

    
   

Lets see the above things in action.

      



·         1. Create a new package name it as listener.


2. Create a new class properties.java


This is used to intialize the Webdriver.

Source code for properties.java

package listner;

import org.openqa.selenium.WebDriver;

public class Properties {
      
       public static WebDriver driver;

}






 Create a simple class named as Listner and extends TestListenerAdapter



3 . extends TestListenerAdapter




After extends TestListenerAdapter am going to override some methods.
*  onTestSuccess(ITestResult tr)
*  onTestFailure(ITestResult itr)

Source code for MyListner.java

package listner;
import java.io.File;
import java.io.IOException;
import java.util.UUID;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.ITestResult;
import org.testng.TestListenerAdapter;


public class MyListner extends TestListenerAdapter{
      
      
      
       public void onTestSuccess(ITestResult tr)  {
               
                System.out.println("TestPassed");
               }
      
       //Am going to take screenshot on failure
       public void onTestFailure(ITestResult itr)
       {
             
             
              File scrFile = ((TakesScreenshot)Properties.driver).getScreenshotAs(OutputType.FILE);
              // Now you can do whatever you need to do with it, for example copy somewhere
              try {
                     FileUtils.copyFile(scrFilenew File("D:\\failure.png"));
              } catch (IOException e) {
                     // TODO Auto-generated catch block
                     e.printStackTrace();
              }
              System.out.println("Taken screenshot because testcase failed");
             
       }

}


Make a new class named as Logintest in which your testcases are running and  write the @Testng annotations and create two Testcases in this class

 4. Create a new Class name it us Logintest





Source code for logintest.java

package listner;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.AfterTest;
import org.testng.annotations.Test;


public class Logintest extends Properties{
      
       public WebDriver driver;
       public Logintest()
       {
              Properties.driver = new FirefoxDriver();
              driver = Properties.driver;
       }
      
       @Test(priority=0)
       public void verifytextsucess()
       {
              driver.get("http://www.gmail.com");
              //Verify the heading is correct
              WebElement text=driver.findElement(By.xpath("html/body/div[1]/div[2]/div[1]/h1"));
              String Heading=text.getText();
              System.out.println(Heading);
              Assert.assertEquals(Heading"One account. All of Google.");
       }
      
       @Test(priority=1)
       public void loginfail()
       {
              //This test will fail because there is no signin webelement
              driver.get("http://www.gmail.com");
              driver.findElement(By.name("Email")).sendKeys("kk.prashanth65@gmail.com");
           driver.findElement(By.name("Passwd")).sendKeys("smartboys");
           //signin webelement is not present
           driver.findElement(By.name("signin")).click();
          
       }
      
       @AfterTest
       public void endtest()
       {
              driver.quit();
       }
}


5.  The below is the Test.xml file.

In the above Test.xml file, We need to pass the class name where we have the test methods. And also we should define listeners in testng.xml file so that TestNG can use them to rewrite the annotations.

<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="My Test Suite">
  <listeners>
    <listener class-name="listner.MyListner" />
  </listeners>
<test name="Logintest">
    <classes>
        <class name="listner.Logintest" ></class> 
    </classes>
</test>
</suite>



Now right click in Test.xml - > RunAs -> TestNG Suit






Once you run. your Test output look like below.


It will also take the screenshot once its complete the Test


The screenshot looks like above..Because the Webelement button name is incorrect in Test.




Hope you Like this post.

Hit LIKE Button on facebook page to stay connected.

Thanks.











7 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. HI Nice blog, very helpful to those looking to work on Selenium Java, Here is a blog to those working on Selenium C# http://iamautomationgeek.blogspot.in

    ReplyDelete
  3. Prashanth please feel free to post you blog URL at my blog --> http://iamautomationgeek.blogspot.in , I have some visitors who might be interested in your posts.

    ReplyDelete
  4. A nice article here with some useful tips for those who are not used-to comment that frequently. Thanks for this helpful information I agree with all points you have given to us. I will follow all of them.
    Selenium Training in Velachery

    ReplyDelete
  5. Looking for
    best selenium training in Chennai, Credo Systemz is the no 1 selenium Training institute in Chennai offering professional selenium course by selenium experts.

    ReplyDelete
  6. Merkur | Merkur - The Most Excellent Safety Razor Ever!
    Merkur Merkur 메리트 카지노 is a beautifully finished, 바카라 사이트 highly-appointed Merkur with a long lasting history of quality. The Merkur Progress is the Merkur first 카지노사이트 and only

    ReplyDelete
  7. A Look at how to win at a casino - Dr.MD
    At the end of your 원주 출장샵 stay in a casino, 안동 출장샵 there will be a 동두천 출장샵 small number 광양 출장안마 of cash available for you to use to win cash or 양산 출장마사지 prizes. It's important to note

    ReplyDelete