Showing posts with label Interview Ques-Ans for Automation Tester. Show all posts
Showing posts with label Interview Ques-Ans for Automation Tester. Show all posts

Sunday, May 18, 2014

How to improve performance of the script in selenium webdriver?

1.How to improve performance of the script in selenium webdriver?
2.isDiplayed() takes more time when element is not present how to over come this?

Ans-  1. use By.id(String arg) locator while locating any element. Avoid to use xpath in script because that always take time and reduce the performance but if xpath is required then use xpath.
2. isDisplayed() obviously will wait till the time webelement will not be visible so for this also use By.id to locate the element fast. One reason could be your internet speed.

How to delete cookies.

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Cookies {
    public static void main(String[] args) {
        WebDriver driver = new FirefoxDriver();
        driver.get("https://www.google.co.in/");
        System.out.println("cookies before delete: "+driver.manage().getCookies());
        driver.manage().deleteAllCookies(); //
        System.out.println("cookies after delete: "+driver.manage().getCookies());
    }
}

How to handle calender popup or date picker ?

Note- 1st click on the calendar button then click on the date which you want to select.
Here in the below example, it will always select the current date , you can pass any date which you want to select as per your requirement.


import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

    public class TodayDate {
    public static void main(String[] args) {
        int day, month, year;
          GregorianCalendar date = new GregorianCalendar();
          day = date.get(Calendar.DAY_OF_MONTH);
          month = date.get(Calendar.MONTH)+1;
          year = date.get(Calendar.YEAR);
          String today = "a_"+year+"_"+month+"_"+day;
          System.out.println(today);
    WebDriver driver = new FirefoxDriver();
    driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
    driver.get("http://www.yatra.com/");
    driver.findElement(By.id("BE_flight_depart_date")).click();
    driver.findElement(By.xpath("//a[@id='"+today+"']")).click();
   
    }

    }

There are 100 testcases i want to execute only 3 test cases without using testng groups?

Note- just include those methods in testng.xml which you want to execute.

For ex- inside com.CC.scripts.Login class there are 100 test cases but you want to execute only 3 methods- at_loginValid, at_loginBlank and at_loginInValid. In that case you can edit your xml as below-

<suite name="Suite" parallel="none">
<test name="Test">
<classes>
<class name="com.CC.scripts.Login">
<methods>
<include name="at_loginValid"></include>
<include name="at_loginInValid"></include>
<include name="at_loginBlank"></include>
</methods>
</class>
</classes>
</test>
</suite>


Login class- Here hello method will not execute by using above testng.xml

package com.CC.scripts;
import org.testng.annotations.Test;

public class Login {
    @Test
    public void at_loginValid(){
        System.out.println("at_loginValid");
    }
    @Test
    public void at_loginInValid(){
        System.out.println("at_loginInValid");
    }
    @Test
    public void at_loginBlank(){
        System.out.println("at_loginBlank");
    }
    @Test
    public void hello(){
        System.out.println("hello");
    }
}

Saturday, May 17, 2014

What is the alternate way to send text in textbox of webpage with out using sendKeys() method ?

Note- Use Javascript to send text.

syntax-

((JavascriptExecutor)driver).executeScript("document.getElementById('attribute value of id').value='text which you want to pass'");

ex-
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class WithoutSendKeys {
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("https://accounts.google.com/ServiceLogin?sacu=1&scc=1...");
((JavascriptExecutor)driver).executeScript("document.getElementById('Email').value='sanjay'");
}
}

Thursday, May 15, 2014

How to execute a test case multiple times or use of 'invocationCount'

Note- invocationCount , this determined how many times the test case should execute.

ex- This will execute 5 times.

import org.testng.annotations.Test;

public class RunTestMultipleTimes {
    @Test(invocationCount=5)
    public void runMultipleTimes(){
        System.out.println("run this test");
    }
}

Output
---------

run this test
run this test
run this test
run this test
run this test
PASSED: runMultipleTimes
PASSED: runMultipleTimes
PASSED: runMultipleTimes
PASSED: runMultipleTimes
PASSED: runMultipleTimes

How to skip a test case in TestNG or use of parameter 'enabled'

Note- By default every @Test has enabled=true.

ex-

import org.testng.annotations.Test;

public class Enabled {
    @Test                            
    public void defaultEnabled(){
        System.out.println("by default enabled=true");
    }
    @Test(enabled=true)
    public void trueEnabled(){
        System.out.println("hard coded enabled=true");
    }
    @Test(enabled=false)
    public void falseEnabled(){
        System.out.println("this test case will be skipped because enabled=false");
    }
}

How to change the position of the open browser window.

Note - use command -> driver.manage().window().setPosition(new Point(int value1,int value2));

import java.awt.AWTException;
import org.openqa.selenium.Point;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class MoveWindow
{
public static void main(String[] args) throws InterruptedException, AWTException
{
    WebDriver driver = new FirefoxDriver();
    driver.manage().window().setPosition(new Point(0,0)); //move the window to top right corner
    Thread.sleep(2000);
    driver.manage().window().setPosition(new Point(500,400)); //move the window to 500unit horizontally and 400unit vertical
}
}

Wednesday, May 14, 2014

How to execute the testcases parallely in TestNG

Test cases can be run parallel by updating testng.xml.

ex- Here two browsers will open as thread-count = "2" (you can change it according to your requirement). In one browser all the classes will be executed which are under 1st test and in 2nd browser, all the classes will be executed which are under 2nd test.

<suite name="Suite" parallel="tests" thread-count="2">
  <test name="Test1">
    <classes>
      <class name="Library.Module1"/>
    </classes>
  </test>
  <test name="Test2">
    <classes>
      <class name="Library.Module2"/>
    </classes>
  </test>
</suite>


Go back to Interview Ques-Ans for Automation Tester

Go to Example with Real Scenario

Tuesday, May 13, 2014

How to download pdf file in desired location without using AutoIt tool.

Note- This code will download the pdf file inside 'C' drive. You can change the directory by changing the path here. profile.setPreference( "browser.download.dir", "download location path" )

import java.util.Iterator;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.interactions.Actions;

public class DownloadPdf {
    public static void main(String[] args) {
        FirefoxProfile profile = new FirefoxProfile();
        profile.setPreference( "browser.download.folderList", 2 );
        profile.setPreference( "browser.download.dir", "C:\\" ); //this will download pdf inside 'C' driver. You can give your path where u want to save the file.
        profile.setPreference( "plugin.disable_full_page_plugin_for_types", "application/pdf" );
        profile.setPreference("browser.helperApps.neverAsk.saveToDisk",  
        "application/csv,text/csv,application/pdfss, application/excel" );
        profile.setPreference( "browser.download.manager.showWhenStarting", false );
        profile.setPreference( "pdfjs.disabled", true );
       
        WebDriver driver = new FirefoxDriver(profile);
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
       
        //login
        driver.get("http://myaccount.rinfra.com/myaccnt/login.do");
        driver.findElement(By.id("username")).sendKeys("150811386");
        driver.findElement(By.name("password")).sendKeys("150811386");
        driver.findElement(By.xpath("//input[@alt='Enter']")).click();
       
       
        driver.findElement(By.xpath("//div[text()='close']")).click(); //close pop-up window
       
        Actions act = new Actions(driver);
        WebElement ele = driver.findElement(By.xpath("//span[contains(text(),'bill & payments')]"));
        act.moveToElement(ele).perform(); //move cursor over bill & payment
        driver.findElement(By.xpath("//a[text()='download / print bill']")).click(); //clicking on 3rd element in the list
        driver.findElement(By.xpath("//a[@class='jqTransformSelectOpen']")).click(); // clicking on select drop down     
        driver.findElement(By.xpath("//a[@index='1']")).click();     //selecting 1st element        
        driver.findElement(By.xpath("//img[@src='images/view.gif']")).click(); // clicking on view
       
        //handle the windows
        Iterator<String> it = driver.getWindowHandles().iterator();
        String mainPage = it.next();
        String child = it.next();
        driver.switchTo().window(child); //switch to child window
        driver.findElement(By.xpath("//button[@id='download']")).click(); //click on download button
        driver.quit();
    }
}

Monday, May 12, 2014

How to pass the Data to test script through xml or How to use @Parameters in TestNG ?

Ans- use @Parameters to pass the input through xml.

Ex-

import org.testng.annotations.Parameters;
import org.testng.annotations.Test;

public class PassInputThruXML {
@Test
@Parameters({"para1","para2"})
public void passInput(String para1, double para2){
    System.out.println(para1);
    System.out.println(para2);
}
}


testng.xml->


<suite name="Suite" parallel="none">
  <test name="Test">
    <parameter name="para1" value="selenium-makeiteasy" />
    <parameter name="para2" value="5.0" />
      <classes>
          <class name="TestNg.PassInputThruXML"/>
      </classes>
  </test>
</suite>

How to get the dropdown value in notepad ?

Note: FileWriter("path of the directory with filename.txt");

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;


public class DropdownNotepad extends Thread {
    public static WebDriver driver;
    public static void main(String[] args) throws IOException {
        driver = new FirefoxDriver();
        driver.get("http://www.etouch.net/home/index.html");
        WebElement service = driver.findElement(By.xpath("//a[text()='Services']"));
        Actions act = new Actions(driver);
        act.moveToElement(service).perform();
        List<WebElement> dropdown = driver.findElements(By.xpath("//li[@id='services']//ul//ul/li"));
        System.out.println(dropdown.size());
       
        FileWriter fileWriter = new FileWriter("C:\\selenium\\out1.txt");
        BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
       
       
       
        for(WebElement ele: dropdown){
            System.out.println(ele.getText());
            bufferedWriter.write(ele.getText()+"\n");
        }
        bufferedWriter.close();
       
        driver.close();
    }
}

How to verify BreadCrumb ?

ex- Home>Services>Enterprise Web, this kind of sequence is called as breadcrumb.

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;

public class BreadCrumb {
    public static void main(String[] args) {
        WebDriver driver = new FirefoxDriver();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.get("http://www.etouch.net/home/index.html");
        WebElement service = driver.findElement(By.xpath("//a[text()='Services']"));
        Actions act = new Actions(driver);
        act.moveToElement(service).perform();
        driver.findElement(By.xpath("//li[a[text()='Services']]//a[text()='Enterprise Web']")).click();
       
       
        String breadcrumb = driver.findElement(By.xpath("//div[@class='breadcrumb']")).getText();
        System.out.println(breadcrumb);
       
        String lastBreadcrumb = driver.findElement(By.xpath("//div[@class='breadcrumb']/span[last()]")).getText();
        System.out.println(lastBreadcrumb);
        if(lastBreadcrumb.equals("Enterprise Web")){
            System.out.println("bread crumb is in correct order.");
        }else{
            System.out.println("bread crumb is not in correct order.");
        }
    }
}

Write a program to check number is Palindrome or not / Write a program to reverse a number.

import java.util.Scanner;

class Palindrome{
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        System.out.println("enter a number");
        int n = in.nextInt();
        int a = n;
        int palindrome =0;
        int r = 0;
        while(n>0){
            r = n%10;
            n = n/10;
            palindrome = palindrome*10 + r;
        }
        System.out.println("Reverse of the entered num is: "+palindrome);
        if(palindrome==a){
            System.out.println(a+" number is palindrome.");
        }else{
            System.out.println(a+" number is not palindrome.");
        }
    }
}

How to swap the two numbers without using 3rd variable.

import java.util.Scanner;

public class Swapping{
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        System.out.println("enter 1st number a: ");
        int a = in.nextInt();
        System.out.println("enter 2nd number b: ");
        int b = in.nextInt();
       
        System.out.println("before swapping a="+a+" and b= "+b);
        a = a+b;
        b = a-b;
        a = a-b;
        System.out.println("after swapping a="+a+" and b= "+b);
    }
}

How to scroll down and up in any web page.

Note- window.scrollBy(forUp,forDown). Here in this method forUp, you can give any value depends on how much you want to scroll up but before that you have to scroll down so that there would be some space to scroll up.
Ex-

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class ScrollDown {
    public static void main(String[] args) throws InterruptedException {
        WebDriver driver = new FirefoxDriver();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.get("http://www.flipkart.com/womens-clothing/pr?sid=2oq,c1r&otracker=hp_nmenu_sub_women_1_View%20all");
        driver.manage().window().maximize();
        JavascriptExecutor jsx = (JavascriptExecutor)driver;
        jsx.executeScript("window.scrollBy(0,4500)", "");
        Thread.sleep(3000);
        jsx.executeScript("window.scrollBy(2000,0)", "");
    }
}

How to open a link in new tab.



import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;

public class NewTab {
    public static void main(String[] args) {
        WebDriver driver = new FirefoxDriver();
        driver.get("http://www.google.com");
        Actions act = new Actions(driver);
        WebElement link = driver.findElement(By.id("gb_70"));
        act.moveToElement(link).contextClick().sendKeys("T").perform();
    }
}

How to move the pointer as well while moving the cursor or How to use Robot class.

Ans- To move the pointer with the cursor we have to use the Robot class.
Ex-

import java.awt.AWTException;
import java.awt.Robot;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.Point;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Myntra {
    public static void main(String[] args) throws InterruptedException, AWTException, IOException {
        WebDriver driver = new FirefoxDriver();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.navigate().to("http://www.myntra.com/");
        WebElement women = driver.findElement(By.xpath("//div[@class='head']//a[4][@href='/shop/women?src=tn&nav_id=34']"));
       
        Point coordinate = women.getLocation();
        Robot robot = new Robot();
        robot.mouseMove(coordinate.getX()+30, coordinate.getY()+120);
        Thread.sleep(10000);
        driver.findElement(By.xpath("//a[@href='/women-jeans?src=tn&nav_id=48']")).click();
        driver.findElement(By.xpath("//div[@id='login']//div[@class='close']")).click();
       
    }
}

Integrate Automation framework with Build using Jenkins.

‘Jenkins’ is a tool which is used for continuous integration testing.

Please follow the below steps to configure the Jenkins with your Automation Framework-

Step1- click on this link : http://jenkins-ci.org/
Step2- click on ‘Long term support release’ tab which is there in right side.
Step3- click on 'older but stable' then one pop-up will come to save the file & there in pop-up click ‘OK’ which will save Jenkins the war file in the Downloads folder, copy paste the downloaded file inside the project.
Step4- Open the command prompt (cmd) and go to project directory.
For ex- say your project directory is -> C:\selenium\SpiceJet\Owler
so here you open cmd, then give command as cd C:\selenium\SpiceJet\Owler and hit enter
Step5- Then type the command ‘java –jar jenkins.war’ & hit enter.
Step6- If Jenkins server is loaded successfully it will display following message in command prompt.      Jenkins is fully up and running

Step7- Now open the browser & enter the following URL in the address bar “local host:8080” which will display homepage of the Jenkins server.
Step8- Click on New Job & specify the job name
For ex: AutomationFramework
Step9- Select the first radio button ‘Build a free-style software project’ then click on OK.
Step10- Click on ‘Advanced’ & select last checkbox 'use custom workspace' under ‘Advanced Project options’ section.
Step11- Type the java project path in the directory (For ex- the java project path –
C:\selenium\SpiceJet\Owler)
Step12- Go down, There you will find Build section, there click on ‘Add Build Step’ & select ‘Execute Windows Batch Command’ & type ‘RunMe.bat’ in the command field.
**How to create RunMe.bat file -
             a) open notepad
             b) paste this command- java -cp bin;jars/* org.testng.TestNG testng.xml
             c) save the file as RunMe.bat
Step13- Go down and click on Save button.
Step14- Now you are all set to use Jenkins. Click on Build Now. It will start the execution of your framework.
Note- In order to create a Build, Developer clicks on ‘Build Now’ which will start the Build creation process once the build is created it will start Framework execution automatically. Every time when we run the build, Jenkins will display a link under Build History, the name of the link will be current system Date & Time, when we click that link it will take us to Build details page where if we click on ‘Console output’ link it will display output of the Automation Framework which is printed on the command prompt.

Please find snapshot below, where you should put .bat file and jenkins.war

screenshot of project

Please leave your valuable feedback. Thanks!!

Sunday, May 11, 2014

How to get the tooltip for all the images present in the webpage.

Note- code has been done in such a way so that it will not print those title which are blank.


import java.util.List;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.
WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Deepika {
    public static void main(String[] args) {
        WebDriver driver = new FirefoxDriver();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.get("http://www.swissoutpost.com/");
        List<WebElement> imgs = driver.findElements(By.tagName("img"));
        System.out.println(imgs.size());
        int num =0;
        String toolTip="";
        for(int i=0; i<imgs.size(); i++){
            toolTip = imgs.get(i).getAttribute("title");
            num+=1;
            if(toolTip.equals("")){
            }else{
                System.out.println(toolTip);
            }
        }
        System.out.println(num);
    }
}