Automation Using Selenium Webdriver

Sunday, 30 October 2016

Email the selenium automation reports through SMTP

Email the selenium automation reports through SMTP
In this post I am going to explain how can we Email the reports after Selenium test execution
with the help of Java using java Mail libraries.

Download Javax Mail jar libraries in following link  and configure to your project.
Download Javax Mail Jar

In this post we are going to send Email through Gmail. So we have to configure SMTP settings of it.Please find the below SMTP Settings of Gmail.

Gmail SMTP settings

Please find the sample code for the same.

Sample Code:

import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class SendMailUtility {


 //Send mail
 public  boolean sendMail(String userName,
        String passWord,
        String host,
        String port,
        String starttls,
        String auth,
        boolean debug,
        String socketFactoryClass,
        String fallback,
        String[] to,
        String[] cc,
        String[] bcc,
        String subject,
        String text,
        String attachmentPath,
        String attachmentName){
              Properties props = new Properties();
        props.put("mail.smtp.user", userName);
        props.put("mail.smtp.host", host);
               if(!"".equals(port))
        props.put("mail.smtp.port", port);
                if(!"".equals(starttls))
        props.put("mail.smtp.starttls.enable",starttls);
        props.put("mail.smtp.auth", auth);
              if(debug){
              props.put("mail.smtp.debug", "true");
              }else{
              props.put("mail.smtp.debug", "false");      
              }
              if(!"".equals(port))
        props.put("mail.smtp.socketFactory.port", port);
                if(!"".equals(socketFactoryClass))
        props.put("mail.smtp.socketFactory.class",socketFactoryClass);
                if(!"".equals(fallback))
        props.put("mail.smtp.socketFactory.fallback", fallback);
        try
        {
            Session session = Session.getDefaultInstance(props, null);
            session.setDebug(debug);
            //attachment start        
            Multipart multipart = new MimeMultipart();
            MimeBodyPart messageBodyPart = new MimeBodyPart();
            DataSource source =
            new FileDataSource(attachmentPath);
            messageBodyPart.setDataHandler(
            new DataHandler(source));
            messageBodyPart.setFileName(attachmentName);
         
            //Message body
            messageBodyPart.addHeaderLine("Please find the attachement");
            multipart.addBodyPart(messageBodyPart);
       
            // Attachment ends
             MimeMessage msg = new MimeMessage(session);

            msg.setSubject(subject);
            msg.setContent(multipart);
       
            //msg.setText(text);
            System.out.println("text================>"+text);
            msg.setFrom(new InternetAddress(userName));

                        for(int i=0;i<to.length;i++){
            msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to[i]));

                        }
                        for(int i=0;i<cc.length;i++){
            msg.addRecipient(Message.RecipientType.CC, new InternetAddress(cc[i]));
                        }
                        for(int i=0;i<bcc.length;i++){
            msg.addRecipient(Message.RecipientType.BCC, new InternetAddress(bcc[i]));
                        }
            msg.saveChanges();
                        Transport transport = session.getTransport("smtp");
                        transport.connect(host, userName, passWord);
                        transport.sendMessage(msg, msg.getAllRecipients());
                        transport.close();

                        return true;
        }
        catch (Exception mex)

        {
            mex.printStackTrace();

            return false;
        }

 }

 //usage
 public static void main(String[] args){

  SendMailUtility utility = new SendMailUtility();
  //You can send to many number of members at a time by separating comma
  String[] to={"testingteam@gmail.com","tl@gmail.com"};
  String[] cc={"manager@gmail.com"};
        String[] bcc={"testingteam@gmail.com@gmail.com"};

  utility.sendMail(
    "Sampletest@gmail.com",
            "Test@123",
             "smtp.gmail.com",
             "465",
             "true",
             "true",
             true,
             "javax.net.ssl.SSLSocketFactory",
             "false",
             to,
             cc,
             bcc,
             "Automation Reports",                            
             "Please find the attached reports",
             "E:/WorkSpace/Practice/AutomationReports.zip",
             "AutomationReports.zip");

     System.out.println("Report has been sent through mail Successfully");
 
}
}

Friday, 28 October 2016

Cross Browser Testing using Selenium WebDriver

Cross Browser Testing using Selenium WebDriver

In this post I am going to explain how can we do Cross Browser Testing using Selenium.

If we are using Selenium WebDriver,In order to execute test cases using different browsers like Firefox, Chrome, Opera ,Internet Explorer we have to use TestNG framework.

Test.xml :
In TestNG, if we want execute same test case with different browsers we have to use Test.xml file.
Sample Code:
<suite name="CrossBrowserTesting" preserve-order="true" parallel="false" >
 
<test name="Smoketest" preserve-order="true">

<parameter name="browserName" value="firefox"></parameter>
 <!--
 <parameter name="browserName" value="ie"></parameter>
 <parameter name="browserName" value="chrome"></parameter>
 <parameter name="browserName" value="opera"></parameter>
  -->
<classes>

<class name="Configuration.HMSLogin"></class>
   
</classes>

</test>

</suite>

BrowserType.java
We have to pass "browserName" parameters from Test.xml and it will map with the BrowserType.java using @Parameters  annotation.
And the BrowserType.java will look like below
Sample Code:
import java.io.IOException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.opera.OperaDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Parameters;

public class BrowserType {

 public static WebDriver driver;
 @BeforeClass
 @Parameters("browserName")
 public void setup(String browserName) throws IOException, InterruptedException{

  //open Firefox Browser
  //open the browser based on parameter passed in .xml file.
  if(browserName.equalsIgnoreCase("firefox")){
 
   //if you are using selenium 2.0
   driver = new FirefoxDriver();
 
   //if you are using selenium 3.0
   //System.setProperty("webdriver.gecko.driver", "path/to/geckodriver.exe");
   //driver = new FirefoxDriver();
  }
  else if(browserName.equalsIgnoreCase("chrome")){
 
   //open chrome browser
   System.setProperty("webdriver.chrome.driver", "E:/Selenium Training/Driver Files/chromedriver.exe");
   driver= new ChromeDriver();
  }

  else if(browserName.equalsIgnoreCase("ie")){
   //open Internet Explorer Browser
   System.setProperty("webdriver.ie.driver", "E:/Selenium Training/Driver Files/IEDriverServer.exe");
   driver= new InternetExplorerDriver();
 
  }
  else if(browserName.equalsIgnoreCase("opera")){
   //open opera Browser
   System.setProperty("webdriver.opera.driver", "E:/Selenium Training/Driver Files/operadriver.exe");
   driver= new OperaDriver();
 
  }
  //maximizing window
  driver.manage().window().maximize();

  //Navigating URL
  driver.get("http://www.facebook.com/");

  }
}

Testcase:
We have to extends BrowserType class to each test-suite and it will look like below
Sample Testcase code:
import org.openqa.selenium.By;
import org.testng.annotations.Test;

public class HMSLogin extends BrowserType {
 @Test(priority=1)
 public void Login() {

  driver.findElement(By.xpath("//input[@name='username']")).clear();
  driver.findElement(By.xpath("//input[@name='username']")).sendKeys("admin");

  driver.findElement(By.xpath("//input[@name='password']")).clear();
  driver.findElement(By.xpath("//input[@name='password']")).sendKeys("admin");

  driver.findElement(By.xpath("//input[@name='submit']")).click();

}

}


finally execute the Test-suite by using Test.xml file.

TCS selenium webdriver interview questions

Tell me abt your project?
explain architecture of ur project?
what r roles and responsibilities in ur current project?
Exploratory testing?
what is d browser used in your project and how to use other browsersin selenium?
How many modules are there in your project? Can you name some 
How many bugs have you found
Give me egs of critical bugs in your application?
Explain how agile model was implemented in your project.?
How much would you rate yourself as test engineer justify it?
How do you handle Child Browser window?
How do you handle Alert pop up?
How do you test the functionality of a Wall Clock?
Say you have 100 regression test cases n you have 4 days to execute.But you can execute only 20 per day. 
What will you do in this situation? You have to execute all 100.you can’t leave any?
write a script  for google search?
You have 6 drop down list and for each drop down list there are 8 choices.
 How will you test this? How many test cases should be written
         

How To Handle Unexpected Alerts In Selenium WebDriver

I have one example where alert Is displaying when loading software web page. So we can check for alert Inside try catch block after page load as shown In bellow given example. After loading page,
It will check for alert. If alert Is there on the page then It will dismiss It else It will go to catch block and print message as shown In bellow given example.

Run bellow given example In eclipse with testng and observe the result.



import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class unexpected_alert {
 WebDriver driver;

 @BeforeTest
 public void setup() throws Exception {
  driver =new FirefoxDriver();  
  driver.manage().window().maximize();
  driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
  driver.get("http://any website alert");
 }

 @AfterTest
 public void tearDown() throws Exception {
  driver.quit();
 }

 @Test
 public void Text() throws InterruptedException {
  //To handle unexpected alert on page load.
  try{
   driver.switchTo().alert().dismiss();
  }catch(Exception e){
   System.out.println("unexpected alert not present");
  }

  driver.findElement(By.xpath("//input[@name='fname']")).sendKeys("fname");
  driver.findElement(By.xpath("//input[@name='lname']")).sendKeys("lname");
  driver.findElement(By.xpath("//input[@type='submit']")).click();
 }
}

Above given webdriver code Is just for example. It Is just explaining the way of using try catch block to handle unexpected alert.
You can use such try catch block In that area where you are facing unexpected alerts very frequently.

Datepicker Using Selenium Webdriver

Many applications are using jQuery Date pickers for selecting date.So selecting date picker using selenium is a not a difficult task.

In this post, I will explain how can we select date from a Date picker using  selenium webdriver.
Please find the below sample code for the same.


Sample code:
import java.util.concurrent.TimeUnit;
import org.testng.annotations.*;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;

public class HandleDatePicker {
  private WebDriver driver;
  private String baseUrl;


  @BeforeClass
  public void setUp() throws Exception {
 System.setProperty("webdriver.chrome.driver", "D:/Sudharsan/Official/Selenium  jars/chromedriver.exe");
 driver = new ChromeDriver();
    baseUrl = "http://jqueryui.com/datepicker/";
    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
    driver.manage().window().maximize();
  }

  @Test
  public void testUntitled() throws Exception {
    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
    driver.get(baseUrl + "/or");
    driver.findElement(By.cssSelector("span.form-hint")).click();
    driver.findElement(By.id("txtUsername")).clear();
    driver.findElement(By.id("txtUsername")).sendKeys("Admin");
    driver.findElement(By.id("txtPassword")).clear();
    driver.findElement(By.id("txtPassword")).sendKeys("admin");
    driver.findElement(By.id("btnLogin")).click();
    Thread.sleep(5000);
    driver.findElement(By.xpath("//b[contains(.,'Leave')]")).click();

    //selecting date with different formats you can give with any one following
    selectDate("23 Jun 1991");

    //selectDate("23-06-1991");
    //selectDate("23/Jun/1991");
    //selectDate("23/06/1991");
    //selectDate("23 Jun 1991");

  }

  //Reusable Method for Selecting Date
  public void selectDate(String format){
   driver.findElement(By.className("ui-datepicker-trigger")).click();

   //identifying format
   String date[] = null;
   if(format.contains("-")){
     date =format.split("-");
   }
   else if(format.contains("/")){
      date =format.split("/");
   }
   else if(format.contains(" ")){
      date =format.split(" ");
   }
   //Splitting data
   String day=date[0];
   String month=date[1];
   String year=date[2];

   //Selecting data based on format
   if(month.length()==2){
    //selecting month if you are giving input format as dd-mm-yyyy
    new Select(driver.findElement(By.className("ui-datepicker-month"))).selectByIndex(Integer.parseInt(month)-1);
   }
   else if(month.length()!=2){
  //selecting month if you are giving input format as dd-mmm-yyyy
    new Select(driver.findElement(By.className("ui-datepicker-month"))).selectByVisibleText(month);
   }
   //selecting year
   new Select(driver.findElement(By.xpath("//select[@class='ui-datepicker-year']"))).selectByVisibleText(year);

    //click on day
    driver.findElement(By.linkText(day)).click();
     }
}

Thursday, 27 October 2016

Decide What Test Cases to Automate

Decide What Test Cases to Automate

It is impossible to automate all testing, so it is important to determine what test cases should be automated first.
The benefit of automated testing is linked to how many times a given test can be repeated. Tests that are only performed a few times are better left for manual testing. Good test cases for automation are ones that are run frequently and require large amounts of data to perform the same action.
You can get the most benefit out of your automated testing efforts by automating:
  • Repetitive tests that run for multiple builds.
  • Tests that tend to cause human error.
  • Tests that require multiple data sets.
  • Frequently used functionality that introduces high risk conditions.
  • Tests that are impossible to perform manually.
  • Tests that run on several different hardware or software platforms and configurations.
  • Tests that take a lot of effort and time when manual testing.
Success in test automation requires careful planning and design work. Start out by creating an automation plan. This allows you to identify the initial set of tests to automate, and serve as a guide for future tests. First, you should define your goal for automated testing and determine which types of tests to automate. There are a few different types of testing, and each has its place in the testing process. For instance, unit testing is used to test a small part of the intended application. To test a certain piece of the application’s UI, you would use functional or GUI testing.
After determining your goal and which types of tests to automate, you should decide what actions your automated tests will perform. Don’t just create test steps that test various aspects of the application’s behavior at one time. Large, complex automated tests are difficult to edit and debug. It is best to divide your tests into several logical, smaller tests. It makes your test environment more coherent and manageable and allows you to share test code, test data and processes. You will get more opportunities to update your automated tests just by adding small tests that address new functionality. Test the functionality of your application as you add it, rather than waiting until the whole feature is implemented.
When creating tests, try to keep them small and focused on one objective. For example, separate tests for read-only versus read/write tests. This allows you to use these individual tests repeatedly without including them in every automated test.
Once you create several simple automated tests, you can group your tests into one, larger automated test. You can organize automated tests by the application’s functional area, major/minor division in the application, common functions or a base set of test data. If an automated test refers to other tests, you may need to create a test tree, where you can run tests in a specific order.

How to pass two strings (Username and Password) one by one in the two different text fields (Username and Password) in webdriver (Java)

I am having two different Strings by name username and password. And i want to pass these string values one by one (ONLY one value from username and one value from password) into username and password text fields. I tried in two different ways but not sure where i am doing mistake. Below are my codes and O/P result. Expected: Two combinations (1st: @ and @, 2nd: test and test).
Expected O/P: username password username password
String[] username={"@", "test"};
String[] password= {"@", "test"};
1st method:
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class TwoStrings {
public static void main(String[] args) {
String[] username={"@", "test"};
String[] password= {"@", "test"};
WebDriver d =new FirefoxDriver();
d.get("http://newtours.demoaut.com/mercurysignon.php");
d.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
for(String j:username){
d.findElement(By.name("userName")).clear();
d.findElement(By.name("userName")).sendKeys(j);
System.out.println("userName");
for(int i =0; i<password.length; i++){
d.findElement(By.name("password")).clear();
d.findElement(By.name("password")).sendKeys(password[i]);
System.out.println("password");
}
}
d.findElement(By.name("login")).click();
}
}
O/P: userName password password userName password password
2nd method which i tried:
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class TwoStrings {
public static void main(String[] args) {
String[] username={"@", "test"};
String[] password= {"@", "test"};
WebDriver d =new FirefoxDriver();
d.get("http://newtours.demoaut.com/mercurysignon.php");
d.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
for(String j:username){
for(String k:password){
d.findElement(By.name("userName")).clear();
d.findElement(By.name("userName")).sendKeys(j);
System.out.println("userName");
d.findElement(By.name("password")).clear();
d.findElement(By.name("password")).sendKeys(k);
System.out.println("password");
}
}
d.findElement(By.name("login")).click();
}
}
O/P: userName password userName password userName password userName password