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

Instantiate Specific Browser Or Client

Instantiate Specific Browser Or Client


Firefox Driver

  1. WebDriver driver = new FirefoxDriver();  
Chrome Driver

  1. WebDriver driver = new ChromeDriver();  
Safari Driver

  1. WebDriver driver = new SafariDriver();  
Internet Explorer Driver


WebDriver driver = new InternetExplorerDriver();

Android Driver

  1. WebDriver driver = new AndroidDriver()  
iPhone Driver

  1. WebDriver driver = new IPhoneDriver();  
HTML Unit

  1. WebDriver driver = new HtmlUnitDriver()  

Reading from XML to trigger a Selenium driver

Reading from XML to trigger a Selenium driver


xml:















Java code:
/*

* @ Author : Sumit Mittal

* @ Description : A simple program to read XML and retrieve data to manipulate Selenium webdriver

* @ Date : 1/03/2014

*/

import java.io.File;

import javax.xml.parsers.DocumentBuilder;

import javax.xml.parsers.DocumentBuilderFactory;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.firefox.FirefoxDriver;

import org.openqa.selenium.*;

import org.w3c.dom.*;



public class GmailXMLTest {



public static void main(String argv[]) {



try {

File file = new File("C:\\TestData.xml"); //file location should be specified correctly

// Prepare XML

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

DocumentBuilder db = dbf.newDocumentBuilder();

Document document = db.parse(file);

document.getDocumentElement().normalize();

System.out.println("Debug: Root element"+ document.getDocumentElement().getNodeName());

NodeList node = document.getElementsByTagName("TestData");

System.out.println("TestData Details");

System.out.println("________________________________________________");



//Read XML to get test data



for (int i = 0; i < node.getLength(); i++) {

Node currentNode = node.item(i);



if (currentNode.getNodeType() == Node.ELEMENT_NODE) {



Element element = (Element) currentNode;

NodeList mailServerElemntList = element.getElementsByTagName("service");

Element mailServer = (Element) mailServerElemntList.item(0);

NodeList mailServer1 = mailServer.getChildNodes();

String Service = ((Node)mailServer1.item(0)).getNodeValue();

System.out.println("Mail Servername:"+ Service);



NodeList emailNodeElementList = element.getElementsByTagName("email-id");

Element emailNodeElement = (Element)emailNodeElementList.item(0);

NodeList details = emailNodeElement.getChildNodes();

String emailAddress=((Node) details.item(0)).getNodeValue();

System.out.println("email :" + emailAddress);



NodeList passwordNodeElementList = element.getElementsByTagName("password");

Element passwordNodeElement = (Element) passwordNodeElementList.item(0);

NodeList address = passwordNodeElement.getChildNodes();

String passCode = ((Node) address.item(0)).getNodeValue();

System.out.println("Password : "+passCode);



NodeList destFolder = element.getElementsByTagName("folder");

Element destElement = (Element) destFolder.item(0);

NodeList city = destElement.getChildNodes();

String destnFolder = ((Node) city.item(0)).getNodeValue();

System.out.println("Folder : " + destnFolder);



FirefoxDriver wd = new FirefoxDriver();

wd.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);

wd.get(Service);

wd.findElement(By.id("Email")).sendKeys(emailAddress);

wd.findElement(By.id("Passwd")).sendKeys(passCode);

wd.findElement(By.id("signIn")).click();

Thread.sleep(8000);

System.out.println(wd.getTitle());

System.out.println(wd.getCurrentUrl());

if (!wd.getCurrentUrl().equals("https://mail.google.com/mail/?shva=1#inbox")) {

wd.close();

System.out.println("Failed to navigate to inbox");

throw new RuntimeException("assertTitle failed");

}

System.out.println("Test Completed - login passed and navigated to inbox");

wd.close();



}

}}

catch (Exception e) {e.printStackTrace();}

}

}

How to Run .exe file through Selenium Webdriver

How to Run .exe file through Selenium Webdriver

Use the below code :)
java.lang.Runtime.getRuntime().exec("D:/Automation Project WorkSpace/AceQATesting/upload.exe");


Working with Dropdown using Selenium Webdriver

Working with Dropdown using Selenium Webdriver


Just wrap your WebElement into Select Object as shown below

Select dropdown = new Select(driver.findElement(By.id("identifier")));
Once this is done you can select the required value in 3 ways. Consider an HTML file like this

Below is the drop down :)





Now to identify dropdown do
Select dropdown = new Select(driver.findElement(By.id("designation")));
To select its option say 'Programmer' you can do
dropdown.selectByVisibleText("Programmer ");
or
 dropdown.selectByIndex(1);
or
  dropdown.selectByValue("prog");

How to Take Screenshot using WebDriver

How to Take Screenshot using WebDriver


Below is the code use it in you function to get the screenshot:

File ScreenShot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
StringBuilder FileName = new StringBuilder("Path or FolderLocation");
FileName.append(ScreenshotFirstName);
FileName.append("_");
FileName.append(dateFormat.format(date).toString());
FileName.append(".jpeg");
FileUtils.copyFile(ScreenShot, new File(FileName.toString()));