Thursday, February 13, 2014

Java Script Executor in Selenium Webdriver

Sometime there is problem to click on hidden element. so to click on hidden element you can use java script as below:

 1. identify element through driver.findelement , suppose its name is element.


2. use below code it will perform click event on hidden element.


 ((JavascriptExecutor)driver).executeScript("arguments[0].click();", element);

Wednesday, February 12, 2014

Multiple Browser Passing as Parameters

Multiple Browser Passing as Parameters


The Parameter "browser" is passed from TestNG.xml as below:



Then use the below code :

@Parameters("browser")
    @BeforeClass
    public void beforeTest(String browser) {
           if (browser.equalsIgnoreCase("firefox")) {
            FirefoxProfile firefoxProfile = new ProfilesIni().getProfile("default");
            driver = new FirefoxDriver(firefoxProfile);
           } else if (browser.equalsIgnoreCase("chrome")) {
                  // Set Path for the executable file
                  System.setProperty("webdriver.chrome.driver","D:\\Automation Project WorkSpace\\Experience\\lib\\chromedriver.exe");
                  driver = new ChromeDriver();
           } else if (browser.equalsIgnoreCase("ie")) {
                  // Set Path for the executable file
                  System.setProperty("webdriver.ie.driver", "D:\\Automation Project WorkSpace\\Experience\\lib\\IEDriverServer.exe");
                  driver = new InternetExplorerDriver();
           } else {
                  throw new IllegalArgumentException("The Browser Type is Undefined");
           }
           // Open App
           driver.get("https://www.google.com");
    }

Thursday, January 9, 2014

Build.xml Files

You can use my Build.xml file and edit it :


you can download it from here


Creating testng.xml to Run Test Suite

The main advantage of using TestNG framework in Selenium is its ease of running multiple tests from multiple classes using just one configuration (We can also have many configurations, which depends upon how we design our test). Testng.xml is an XML file that describes the runtime definition of a test suite. It describes complex test definition while still remain easy to edit.
Using Testng.xml file we can run test available in one or more class file and make them as a single group, hence making test more meaningful, we call them as scenario based testing.
Can I run test without using testng.xml file?
Well answer is yes, you can run. But once your test become larger and requires configuration of multiple test at one place, the best option is testng.xml.
The testng.xml file will have following hierarchy
  • The root tag of this file is .
  • tag can contain one or more tags.
  • tag can contain one or more tags.
  • tag can contain one or more tags.
  • For more information on Tags and other tags that you can use in your XML file, check out the details here
    Your xml file with just one test in a one class file will look something like this.

    As you could see above, the Class name has Test.NewTest, which is nothing but the “Fully qualified” name of the Class. It means NewTest is the class file which is available under package Test.
    Now your  Eclipse IDE should look something like this.

    I have added the testng.xml file in our project, so that we can use it for running test.

    Try Running Test using Testng.xml

    Just right click on the testng.xml file in package explorer of Eclipse and select Run As Testng Suite, the test will run .

    if you want to pass parameters create xml file like this:



My .java test file looks like this:
public class Gmail
{
public WebDriver driver;

 
 
@Test
@Parameters({"Urlsite"})
public void GmailAccess(String value) 
{
driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
try{
driver.get(value);
driver.close();

Wednesday, January 8, 2014

Email your failing Selenium WebDriver scripts’ Stack Trace to your Email Id

This is my new post and I am very excited because through this we would be able to find all Stack Trace of our failing WebDriver Scripts.This has been made possible through one of the Java Mail API.
1- Pre-requisiteFirst we need to download two jar files
1- javaee-api-5.0.3.jar
2- javamail1_4_7.zip
download both file from here
In this Java Mail API we use mainly two packages
1) javax.mail.internet.
2) javax.mail
In general we use three steps to send mails using Javamail API
1- Session Object creation that stores all the information like Host name, username and password
like this
Session session = Session.getDefaultInstance(props,new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(“usermail_id”,”password”);
}
})
2- Setting Subject and Message body like this
message.setSubject(“Testing Subject”); //this line is used for setting Subject line
message.setText(“your test has failed <============================>”+ExceptionUtils.getStackTrace(e) );
3- Sending mail that could be done with this line of code
Transport.send(message);
2- Now I am pasting here my code of Mail sending class

package test_Scripts;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.apache.commons.lang3.exception.ExceptionUtils;
public class SendMail{
public SendMail(String fromMail,String tomail, Exception e )
{
String fileAttachment = "C:\\Users\\Sumit.Mittal\\Desktop\\attach.txt"; 
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("Email_Id","password");
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(fromMail));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(tomail));
message.setSubject("Script failed");
// create the message part   
MimeBodyPart messageBodyPart =  new MimeBodyPart();  
//fill message  
messageBodyPart.setText("Test mail one"+ ExceptionUtils.getStackTrace(e));  
Multipart multipart = new MimeMultipart();  
multipart.addBodyPart(messageBodyPart);  
// Part two is attachment  
messageBodyPart = new MimeBodyPart();  
DataSource source =  new FileDataSource(fileAttachment);  
messageBodyPart.setDataHandler( new DataHandler(source));  
messageBodyPart.setFileName(fileAttachment);  
multipart.addBodyPart(messageBodyPart);  
// Put parts in message  
message.setContent(multipart);  
//message.setText("your test has failed for script name:Name of your scipt <============================>"+ Keys.ENTER+ ExceptionUtils.getStackTrace(e) );
Transport.send(message);
System.out.println("Mail Sent Done");
} catch (MessagingException ex) {
throw new RuntimeException(ex);
}
}
}
I have written one class SendMail with one constructor with three parameter. that I would call in my WebDriver script. and When My code would fail some where then It will send the Stack Trace.
3- My script of WebDriver
package test_Scripts;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class Except {
WebDriver d;
@BeforeMethod
public void launch()
{
System.setProperty("webdriver.chrome.driver", "E:\\SumitMittal\\workspace\\chromedriver_win_26.0.1383.0\\chromedriver.exe");
d = new ChromeDriver();
}
@Test
public void test()
{
d.get("www.gmail.com");
try{
WebElement element= d.findElement(By.xpath("//div/span"));
element.sendKeys("dwarika");
}
catch(Exception e)
{
e.printStackTrace();
new SendMail("Sender_Mailid","Receiver_Mailid",e);
}
}
}
I have tried this code and find that we can use it in our selenium Scripting for sending mail for failing scripts. but I am hoping some more valuable advise from you people to use it in more optimized form..So if you have any other method then please let me know about the same.

Handling JavaScript Alert in WebDriver

Handling JavaScript Alert is big question if you have just started learning WebDriver. Because we always get multiple pop-ups some time we get information about validity of input and some time these pop-up speaks about error, and also about response.
But as a tester we need to verify the alert message and for the same we need to handle the Alert pop up. So its time to celebrate because WebDriver have provided us with Alertclass to deal with JavaScript Alert.

Since I have created this alert through a basic html file and  it has one button Ok. Butthere is another kind of alert known as Confirm Box Alert and it normally have two button
1-Ok button
2- Cancel button
Since both alert is handled in the same way so here I am taking the Confirm Box Alert here
Scenario : Suppose we have one button, and once we hit on the button a alert appears with two button Ok and Cancel
a) In first case if end user click on Ok button
@Test
public void testAlertOk()
{
//Now we would click on AlertButton
WebElement button = driver.findElement(By.id("AlerButton"));
button.click();
try {
//Now once we hit AlertButton we get the alert
Alert alert = driver.switchTo().alert();
//Text displayed on Alert using getText() method of Alert class
String AlertText = alert.getText();
//accept() method of Alert Class is used for ok button
alert.accept();
//Verify Alert displayed correct message to user
assertEquals("this is alert box",AlertText);
} catch (Exception e) {
e.printStackTrace();
}
}
b) In second case we want to click on Cancel button
So above code would remain same only thing that would change in above script is
alert.accept();
For clicking on Cancel we need to use dismiss() method of Alert Class


alert.dismiss();

Hope this script would help you to handle Alert in WebDriver

Implicit Wait in WebDriver

Implicit wait in WebDriver has solved the compile error of Element not found. Element not found kind of error mostly comes in to picture due to slow internet connection or some time due to responses time of Website or web-application and due to which expected element on the website/webpage takes more time to appear. This cause failure of test script written for that specific element on webpage.
Implicit wait in webdriver synchronize test. This implicit wait implementation in test ensure first that element is available in DOM(Data Object Model) or not if not then it wait for the element for a specific time to wait for appearance of element on Webpage.
Normally Implicit wait do the polling of DOM and every time when it does not find any element then it wait for that element for certain time and due to this execution of test become a slow process because implicit wait keep script waiting.Due to this people who are very sophisticated in writing selenium webdriver code advise not to use it in script and for good script implicit wait should be avoided.
Ok come to the point WebDriver API has one Interface named as Timeouts and this is used for implicit wait and since this is interface so have one function named as implicitlyWait(), this method takes the argument of time in Second, and this code is written like this
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
Here I have taken 5 second as wait, once script see any findElement() method then it goes for 5 second wait.
But this keeps script waiting for 5 second once it see a findElement() method so WebDriver API has introduced one explicit wait and in this WebDriverwait class play a very important role.
So in next post I would let you know about the Explicit wait and i would suggest to use explicit wait.

Contains() and starts-with() function in Xpath

Contains() and starts-with() function in Xpath




Here  as we can see we want to search Google Search just by writing its xpath in console
So to find the Google Search button we have to write xpath like this
//span[@id='gbqfsa']
Once we hit enter it would bring
[
  1. gbqfsa">​Google Search​​
],
It shows that xpath for Google Search Button is correctly written
Now suppose we want to search Google Search button if we are just familiar that id attributes start with gbqfs
then we have to use function starts-with like this
//span[starts-with(@id,'gbqfs')]
and once when we hit enter on console it would reflect two button one is Google Searchand Second one is I’m Feeling Lucky
[
  1. gbqfsa">​Google Search​​
,
  1. ​I'm Feeling Lucky​
]
So to find out the Google Search uniquely we need to complete id attribute to gbqfsa
“//span[starts-with(@id,'gbqfsa')]
and hit to enter and now it would reflect only
[
  1. ​Google Search​
],
It proves that we have written right xpath for Google Search
In the same fashion we can use Contains function to find the Google Search button like this
here I have taken fsa from gbqfsa
//span[contains(@id,'fsa')]  hit enter and hopefully it will return 
[
  1. ​Google Search​
],
if there are multiple attributes then we can use:
//span[contains(@id,'fsa') and contains(@class, 'xyz')]  hit enter and hopefully it will return



Launch Chrome Browser Using WebDriver

Launching Chrome Browser using WebDriver
In WebDriver, We launch FireFox and Internet Explorer by using
WebDriver driver = new FirefoxDriver(); //this line would launch Firefox
WebDriver driver = new InternetExplorerDriver(); //this line would launch IE browser
But when we write below line like FireFox and IE
WebDriver driver = new ChromeDriver();
Then It throws Error and Here I am pasting Error Trace shown in Eclipse
java.lang.IllegalStateException: The path to the driver executable must be set by the webdriver.chrome.driver system property; for more information, seehttp://code.google.com/p/selenium/wiki/ChromeDriver. The latest version can be downloaded from http://code.google.com/p/chromedriver/downloads/list
at com.google.common.base.Preconditions.checkState(Preconditions.java:176)
IT seems really tedious na, But there is one way to resolve this Error and this could be done by using this
1- Download zip file of chromedriver for Windows from here
2- Unzip downloaded Chromedriver for Windows and find the absolute path of chromedriver.exe
3- Now set Property of System by using this line
System.setProperty(“webdriver.chorme.driver”,”E:\\SumitMittal\\workspace\\chromedriver_win_26.0.1383.0\\chromedriver.exe”);
and after this line write your traditional line to launch the browser like this
WebDriver driver =new ChromeDriver();
So why not we write one script that help us to see the launching of Chrome


import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class Chrome {
WebDriver driver;
@Before
public void launchChrome()
{
System.setProperty("webdriver.chrome.driver", "E:\\SumitMittal\\workspace\\chromedriver_win_26.0.1383.0\\chromedriver.exe");
driver = new ChromeDriver();
}
@Test
public void testChrome()
{
driver.get("http://www.google.co.in");
driver.findElement(By.id("gbqfq")).sendKeys("Selenium");
}
@After
public void kill()
{
driver.close();
driver.quit();
}
}

This code is verified at my own and if there is any suggestion then please let me know. I would be very happy to hear from you.

Tuesday, January 7, 2014

Check If An Element Exists

Check If An Element Exists

You may need to perform a action based on a specific web element being present on the web page. You can use below code snippet to check if a element with id “element-id” exists on web page. 


driver.findElements(By.id("element-id")).size()!=0