Wednesday, 29 October 2014

Multi Selection

Suppose if we want to select multiple selections in the combo box. To achieve this sample code is given below.


Example: 


List<WebElement> listItems = driver.findElements("find your select by id or xpath or etc");
Actions builder = new Actions(driver);
builder.clickAndHold(listItems.get(1)).clickAndHold(listItems.get(2)).click();
Action selectMultiple = builder.build();
selectMultiple.perform();


To know FAQ's on Selenium Please ClickHere
To know SQL's Queries Required For Testers Please ClickHere

Saturday, 4 October 2014

Auto Complete Suggestion View

In an application We will search for an item in the Search box. We will try to select the third suggestion in the auto complete suggestion view. To get this sample code is given below.


package Logs;

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 Auto {

public static void main(String[] args) throws InterruptedException {

 WebDriver driver=new FirefoxDriver();

 driver.manage().window().maximize();

 driver.get("http://www.flipkart.com/");

// Type something on Search textbox
 driver.findElement(By.name("q")).sendKeys("mobil");

// Create object on Actions class
 Actions builder=new Actions(driver);

// find the element which we want to Select from auto suggestion

 WebElement ele=driver.findElement(By.xpath(".//*[@id='list_?']/li[3]/ac_odd"));

// use Mouse hover action for that element
 builder.moveToElement(ele).build().perform();

// Give wait for 2 seconds
 Thread.sleep(200);

// finally click on that element
 builder.click(ele).build().perform();

}
}

To know FAQ's on Selenium Please ClickHere
To know SQL's Queries Required For Testers Please ClickHere

Tuesday, 23 September 2014

Most Common Java Programs for Testers in Interviews

1.How can you show the duplicate elements from an array by avoiding distinct elements.

     ArrayList<String>list = new ArrayList<String>();
    //list of numbers added in from 0-9
   
        for (int i = 0; i < 10; i++) {
            list.add(String.valueOf(i));
        }
        //another set of numbers from 0-5
        for (int i = 0; i < 5; i++) {
            list.add(String.valueOf(i));
        }

        System.out.println("My List : " + list);
        System.out.println("\nHere are the duplicate elements from list : " + findDuplicates(list));

      For the full code Please ClickHere

2.How can you reverse a number 

        int reverse = 0;
        while(number != 0){
            reverse = (reverse*10)+(number%10);
            number = number/10;
        }
        return reverse;
   
For the full code Please ClickHere

3.How can you sort an collection of array of strings

String[] strArray = { "Abhishek", "selenium", "Automation" };

  displayArray(strArray);

   Arrays.sort(strArray);

   displayArray(strArray);

Arrays.sort(strArray, String.CASE_INSENSITIVE_ORDER);

  displayArray(strArray);

  System.out.println("---------------");

  List<String> strList = new ArrayList<String>();
  strList.add("Abhishek");
  strList.add("Webdriver");
  strList.add("Automation");
  displayList(strList);

 For the full code Please ClickHere

4.Can you reverse a String with and Without using StringBuffer

   With String Buffer
     StringBuffer buffer = new StringBuffer(str);
      buffer.reverse();
     return buffer.toString();

   Without String Buffer
    int length = str.length();
    String original = str;
    String reverse = "";
    for(int i = length-1; i>=0; i--){
    reverse = reverse + original.charAt(i);
    }
   return reverse;

For Full Code Please ClickHere

5.How can you say a number is Prime or not According to user input

    if (isPrime(n)) {
            System.out.println(n + " is a prime number");
        } else {
            System.out.println(n + " is not a prime number");
        }

    if (n <= 1) {
            return false;
        }
        for (int i = 2; i < Math.sqrt(n); i++) {
            if (n % i == 0) {
                return false;
            }
        }
        return true;

For Full Code Please ClickHere

6.How can you a number is Palindrome or not According to user input

for (int i=0; i<=num; i++){
   int r=num%10;
   num=num/10;
   rev=rev*10+r;
   i=0;
   }

For Full Code Please ClickHere

7.How can you show the maximum numbers from the given array

  int maxOne = 0;
  int maxTwo = 0;
  for(int n:nums){
   if(maxOne<n){
    maxTwo = maxOne;
    maxOne = n;
   }else if(maxTwo<n){
    maxTwo = n;
   }
 
  }

For the Full Code Please ClickHere

8.Can you the Longest Substring Without Repetition of Characters in the string

  char[] inputCharArr = input.toCharArray();
for (int i = 0; i < inputCharArr.length; i++) {
char c = inputCharArr[i];
if (flag[c]) {
extractSubString(inputCharArr,j,i);
for (int k = j; k < i; k++) {
if (inputCharArr[k] == c) {
j = k + 1;
break;
}
flag[inputCharArr[k]] = false;
}
} else {
flag[c] = true;
}
}
extractSubString(inputCharArr,j,inputCharArr.length);
return subStrList;

For Full Code Please ClickHere

9. Swapping of Two Numbers Without having a temp Variable

       x = x+y;
        y=x-y;
        x=x-y;
For the Full Code Please ClickHere

10.How can you remove the multiple spaces of String

package Logs;
import java.util.StringTokenizer;

public class Mutiplespaces {
    public static void main(String a[]){
        String str = "Selenium    Webdriver Automation      Testing";
        StringTokenizer st = new StringTokenizer(str, " ");
        StringBuffer sb = new StringBuffer();
        while(st.hasMoreElements()){
            sb.append(st.nextElement()).append(" ");
        }
        System.out.println(sb.toString().trim());
    }
}

Output
Selenium Webdriver Automation Testing

To know FAQ's on Selenium Please ClickHere
To know SQL's Queries Required For Testers Please ClickHere

Find the Longest Substring in the given String Without Repetition of characters

Given a string, find the longest substrings without repeating characters. Iterate through the given string, find the longest maximum substrings.
package Logs;
import java.util.HashSet;
import java.util.Set;

public class longestsubstring {

private Set<String> subStrList = new HashSet<String>();
private int finalSubStrSize = 0;

public Set<String> getLongestSubstr(String input){
//reset instance variables
subStrList.clear();
finalSubStrSize = 0;
// have a boolean flag on each character ascii value
boolean[] flag = new boolean[256];
int j = 0;
char[] inputCharArr = input.toCharArray();
for (int i = 0; i < inputCharArr.length; i++) {
char c = inputCharArr[i];
if (flag[c]) {
extractSubString(inputCharArr,j,i);
for (int k = j; k < i; k++) {
if (inputCharArr[k] == c) {
j = k + 1;
break;
}
flag[inputCharArr[k]] = false;
}
} else {
flag[c] = true;
}
}
extractSubString(inputCharArr,j,inputCharArr.length);
return subStrList;
}

private String extractSubString(char[] inputArr, int start, int end){

StringBuilder sb = new StringBuilder();
for(int i=start;i<end;i++){
sb.append(inputArr[i]);
}
String subStr = sb.toString();
if(subStr.length() > finalSubStrSize){
finalSubStrSize = subStr.length();
subStrList.clear();
subStrList.add(subStr);
} else if(subStr.length() == finalSubStrSize){
subStrList.add(subStr);
}

return sb.toString();
}

public static void main(String a[]){
longestsubstring mls = new longestsubstring();
System.out.println(mls.getLongestSubstr("automation_tester"));
System.out.println(mls.getLongestSubstr("Selenium_Webdriver_is_AutomationTesting"));
System.out.println(mls.getLongestSubstr("sdsjk_uippj_agjhs_7890"));
System.out.println(mls.getLongestSubstr("abcabcbb"));
}
}


OutPut:
[ion_tes, mation_]
[nium_Webdr, um_Webdriv]
[agjhs_7890]
[cab, abc, bca]

To know FAQ's in Interviews on Selenium  ClickHere
To know more on SQL Queries Required For Testers  ClickHere

Duplicate elements in ArrayList by avoiding Distinct elements

In an Array list I mean to show is the elements which are repeating and by avoiding the distinct elements .To show this we require a piece of code.
Example:
package Test;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class DuplicateNumbers {

    public static void main(String[] args) {
   
    ArrayList<String>list = new ArrayList<String>();

    //list of numbers added in from 0-9
   
        for (int i = 0; i < 10; i++) {
            list.add(String.valueOf(i));
        }
        //another set of numbers from 0-5
        for (int i = 0; i < 5; i++) {
            list.add(String.valueOf(i));
        }

        System.out.println("My List : " + list);
        System.out.println("\nHere are the duplicate elements from list : " + findDuplicates(list));
    }

    public static Set<String> findDuplicates(List<String> listContainingDuplicates) {

        final Set<String> setToReturn = new HashSet<String>();
        final Set<String> set1 = new HashSet<String>();

        for (String yourInt : listContainingDuplicates) {
            if (!set1.add(yourInt)) {
                setToReturn.add(yourInt);
            }
        }
        return setToReturn;
    }
}



Output:

My List : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4]

Here are the duplicate elements from list : [3, 2, 1, 0, 4]

To know FAQ's in Interviews on Selenium Please  ClickHere
To know more on SQL Queries Required For Testers Please ClickHere

Thursday, 18 September 2014

How to Write a Effective Test Cases in Manual or Automation

  • Writing effective test cases is a skill and that can be achieved by some experience and in-depth study of the application on which test cases are being written.
  • Here I will share some tips on how to write test cases, test case procedures and some basic test case definitions.

What is a test case?
“A test case has a component that describes an input, action or event and an expected response, to determine if a feature of an application is working correctly.”

There are levels in which each test case will fall in order to avoid duplication efforts

Level 1: In this level you will write the basic test cases from the available specification and user documentation.

Level 2: This is the practical stage in which writing test cases depend on actual functional and system flow of the application.

Level 3: This is the stage in which you will group some test cases and write a test procedure. Test procedure is nothing but a group of small test cases maximum of 10.

Level 4: Automation of the project. This will minimize human interaction with system and thus QA can focus on current updated functionalities to test rather than remaining busy with regression testing.
So you can observe a systematic growth from no testable item to a Automation suit.

Why we write test cases?
The basic objective of writing test cases is to validate the testing coverage of the application. If you are working in any CMMI company then you will strictly follow test cases standards. So writing test cases brings some sort of standardization and minimizes the ad-hoc approach in testing.

How to write test cases?
Here is a simple test case format
Fields in test cases:

  • Test case id:
  • Unit to test: What to be verified?
  • Assumptions:
  • Test data: Variables and their values
  • Steps to be executed:
  • Expected result:
  • Actual result:
  • Pass/Fail:
  • Comments:
So here is a basic format of test case statement:
Verify
Using [tool name, tag name, dialog, etc]
With [conditions]
To [what is returned, shown, demonstrated]
Verify: Used as the first word of the test case statement.
Using: To identify what is being tested. You can use ‘entering’ or ‘selecting’ here instead of using depending on the situation.
  • For any application basically you will cover all the types of test cases including functional, negative and boundary value test cases.
  • Keep in mind while writing test cases that all your test cases should be simple and easy to understand. 
  • Don’t write explanations like essays. Be to the point.
  • Try writing the simple test cases as mentioned in above test case format.
  •  Generally I use Excel sheets to write the basic test cases.
  •  Use any tool like ‘Test Director’ when you are going to automate those test cases.




To know FAQ's on Selenium ClickHere
To know SQL Queries Required For Testers ClickHere 

Wednesday, 17 September 2014

Generation of XSLT Report(Testng+ANT+Selenium)

  • XSLT stands for XML (Extensible Markup Language) Stylesheet Language for Transformations. 
  • XSLT gives interactive(user friendly) reports with "Pie Chart"; but only on TestNG framework. It is better compared to ReportNG and ordinary TestNG reports. 
  • Its uses the pure XSL for report generation and Saxon as an XSL2.0 implementation.                 XSLT = XSL Transformations
  • Language for XML documents. XSLT stands for XSL Transformations.
  •  In this tutorial you will learn how to use XSLT to transform XML 
  • Documents into other formats, like XHTML. XSLT which gives good graphical generated reports.
Steps for generating reports:

Step 1:Ant should be installed ,If it is not installed ,By using
           Ant Installation

Step 2: Download the Xslt .
           XsltReportsZip

Step 3: After UnZip ,You Will get

                                        
             
Step 4: Now copy the Saxon jar add the jars files to your project through build path from the lib folder.                                        
                                             
                                 
Step 5:Modify your build.xml of ant and add the following target to it.
<?xml version="1.0" encoding="UTF-8"?> 
<project>
    <property name="src.dir" value="src" />
    <property name="lib.dir" value="lib" />
    <property name="log.dir" value="logs" />
    <property name="build.dir" value="build" />
    <property name="classes.dir" value="classes" />
    <property name="reports.dir" value="reports" />
    <property name="testNG.report" value="${reports.dir}/TestNG" />
    <property name="suite.dir" value="suite" />
    <!-- Class-Path -->
    <path id="classpath">
        <pathelement location="${classes.dir}"/>
        <fileset dir="${lib.dir}" includes="*.jar"/>
    </path>
    <!-- Delete directories that are not needed -->
    <target name="delete-dir" >
            <delete dir="${build.loc}"/>
            <delete dir="${reports.dir}"/>
            <delete dir="${classes.dir}"/>
            <echo> /* Deleted existing Compiled Directory Classes */ </echo>
    </target>
    <!-- Create Directories -->
    <target name="create-source-dir" depends="delete-dir">
        <mkdir dir="${classes.dir}"/>
        <mkdir dir="${reports.dir}"/>       
        <mkdir dir="${testNG.report}"/>
        <echo> /* Created Directories */ </echo>
    </target>
    <!-- Compiling Tests -->
    <target name="compile-classes" depends="create-source-dir">
        <javac destdir="${classes.dir}" includeantruntime="false" debug="true" srcdir="${src.dir}">
            <classpath refid="classpath"/>
        </javac>
        <echo> /* Compiled Directory Classes */ </echo>
    </target>
    <!-- Running Tests and TestNG report generation -->
    <target name="testNGreport" depends="compile-classes">
        <taskdef resource="testngtasks" classpathref="classpath"/>
        <testng classpathref="classpath" outputDir="${testNG.report}" haltOnfailure="false">
              <xmlfileset dir="." includes="${suite.dir}/TestNG.xml" />
        </testng>
        <echo> /* Run Directory Classes */ </echo>
    </target>
   
         <target name="testng-xslt-report">
                <delete dir="${basedir}/testng-xslt">
                </delete>
                <mkdir dir="${basedir}/testng-xslt">
                </mkdir>
                <xslt in="${basedir}/reports/TestNG/testng-results.xml" style="${basedir}/testng-results.xsl" out="${basedir}/testng-xslt/index.html">
                    <param expression="${basedir}/testng-xslt/" name="testNgXslt.outputDir" />
       
                    <param expression="true" name="testNgXslt.sortTestCaseLinks" />
       
                    <param expression="FAIL,SKIP,PASS,CONF,BY_CLASS" name="testNgXslt.testDetailsFilter" />
       
                    <param expression="true" name="testNgXslt.showRuntimeTotals" />
       
                    <classpath refid="classpath">
                    </classpath>
                </xslt>
            </target>
   
</project>

Step 6:Modify the Testng xml

<?xml version="1.0" encoding="UTF-8"?>
<suite name="Suite" parallel="false">
  <test name="Test">
    <classes>
      <class name="package.classname"/>
    </classes>
  </test> <!-- Test -->
</suite> <!-- Suite -->

Step:7
Open this report in the browser.
         
                                        

The XSLT Report looks like this.



         






To know FAQ's on Selenium ClickHere
To know SQL Queries Required For Testers ClickHere 

Tuesday, 16 September 2014

Logs4j Installation and with an example Test case

  • If we are executing Test Suite with hundreds of automated test cases then logging all the events might be useful.
  • Helps in debugging, in case of test automation failures
  • gives a fair understanding of application run
  • log output can be saved into some external medium and can be studied later on
Components of Log4j 

Loggers- Instance of Logger class.
              -used for printing the log messages. Levels are of following kinds:
error()
warn()
info()
debug()
log()

Appenders- might be a console, a log file, printer, etc.

Layouts- is the formatting of the log output. 

Steps:

Step1. The package distribution is widely available. Thus, download the latest version of log4j jar from here.
Step2. In eclipse, configure build path and add log4j.jar as an external jar. 




Step3 Create an log4j xml file.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="false">

<appender name="fileAppender" class="org.apache.log4j.FileAppender">

<param name="Threshold" value="INFO" />

<param name="File" value="logfile.log"/>

<layout class="org.apache.log4j.PatternLayout">

<param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss}  [%c] (%t:%x) %m%n" />

</layout>

</appender>

<root>

<level value="INFO"/>

<appender-ref ref="fileAppender"/>

</root>


</log4j:configuration>

Step 4:Java class

package Logs;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.log4j.xml.DOMConfigurator;

import java.awt.AWTException;
import java.awt.Robot;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;


public class Loggssample 
{
         //Initialization of Logger Instance.
static final Logger logger = LogManager.getLogger(Loggssample.class.getName());
public static void main(String[] args)  throws IOException, AWTException
{
             ///“DOMConfigurator” to parse the configuration file “log4j.xml” and setup logging.
DOMConfigurator.configure("log4j.xml");

logger.info("# # # # # # # # # # # # # # # # # # # # # # # # # # # ");
logger.info("TEST Has Been Started");

WebDriver driver = new FirefoxDriver();

//Puts a Implicit wait, Will wait for 10 seconds before throwing exception
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

//Launch website
driver.get("https://www.gmail.com");
logger.info("Open gmail application");

//Maximize the browser
driver.manage().window().maximize();

// Enter the username 

driver.findElement(By.id("Email")).clear();

driver.findElement(By.id("Email")).sendKeys("username");
logger.info("Enter the user's username");

// Enter the password
driver.findElement(By.id("Passwd")).clear();

driver.findElement(By.id("Passwd")).sendKeys("password");

logger.info("Enter the user-password");


// Press enter to sign in
Robot robot = new Robot();

robot.keyPress(java.awt.event.KeyEvent.VK_ENTER);
logger.info("Enter sign in");


logger.info("# # # # # # # # # # # # # # # # # # # # # # # # # # # ");

//Close the Browser.
driver.close();    
}

}

======================================================================
2014-09-16 15:30:18,931 INFO [log4jXmlTest] # # # # # # # # # # # # # # # # # # # # # # # # # # #
2014-09-16 15:30:24,773 INFO [log4jXmlTest] TEST Has Been Started
2014-09-16 15:30:24,773 INFO [log4jXmlTest] Open gmail application
2014-09-16 15:30:26,850 INFO [log4jXmlTest] Enter the user's username
2014-09-16 15:30:27,460 INFO [log4jXmlTest] Enter the user-password
2014-09-16 15:30:27,491 INFO [log4jXmlTest] Enter sign in



To know FAQ's on Selenium Please ClickHere
To know SQL's Queries Required For Testers Please ClickHere







Language preferences in selenium


 package Testng
 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.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.testng.annotations.Test;
public class Languagechange {
         

          public static void main(String[] args) throws IOException, AWTException{

                   // This will create firefox profile
                   FirefoxProfile fp=new FirefoxProfile();

                   // this will change the language preference and fr is the locale for france
                   fp.setPreference("intl.accept_languages", "fr");

                   // now pass this fp object to FirefoxDriver
                   WebDriver driver=new FirefoxDriver(fp);

                 //will manage to maximize a window
                   driver.manage().window().maximize();

                   //getting the url
                   driver.get("https://www.gmail.com");
                  
                   driver.findElement(By.id("Email")).clear();

                   driver.findElement(By.id("Email")).sendKeys("username");

                   driver.findElement(By.id("Passwd")).clear();

                   driver.findElement(By.id("Passwd")).sendKeys("password");

                   Robot robot = new Robot();      

                   robot.keyPress(java.awt.event.KeyEvent.VK_ENTER);

                   driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
                  
                   driver.close();



          }

}

To know FAQ's in Interviews on Selenium  ClickHere
To know more on SQL Queries Required For Testers  ClickHere

Monday, 15 September 2014

How can we select required date in calender popup in selenium

package Testng;
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 CalenderPopUp {
    
     public static void main(String[] args) {
     int day, month, year;
    
     String futrDate = "td_"+2015+"_"+06+"_"+24; //this is the 'id' format in the calendar popup in html code, ex- id=td_2015_6_24
    
     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();
     String monthYear="";
     //this loop will execute untill your required month and year will not appear in the calendar
     //here you can also pass the input from your and by making code as common
     while(!(monthYear.equals("Jun 2015"))){
         driver.findElement(By.xpath("//a[@class='js_btnNext sprite nextBtn']")).click(); //this will click on next button for month
         monthYear = driver.findElement(By.xpath("//span[@class='js_monthTitle']")).getText(); // this is to get the month and year from calendar pop up
     }
    
     driver.findElement(By.xpath("//td[@id='"+futrDate+"']")).click(); //this will select the date
     }
}




To know FAQ's in Interviews on Selenium  ClickHere
To know more on SQL Queries Required For Testers  ClickHere

How to count a page load time with selenium webdriver

Suppose their is a situation to see time taken for a web page to load.To achieve this a small piece of code is required :
Example: Situation is time taken for user to login into gmail.

package Logs;
import java.awt.AWTException;
import java.io.IOException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class TrackWebtime {
public static void main(String[] args) throws IOException, AWTException{

WebDriver driver =new FirefoxDriver();

driver.get("http://www.website.com");

long start = System.currentTimeMillis();

 driver.findElement(By.id("Email")).clear();

driver.findElement(By.id("Email")).sendKeys("username");

driver.findElement(By.id("Passwd")).clear();

driver.findElement(By.id("Passwd")).sendKeys("password");

Robot robot = new Robot();

robot.keyPress(java.awt.event.KeyEvent.VK_ENTER);

long finish = System.currentTimeMillis();
 
  long TotalTime = finish - start;

System.out.println("Total Time for page load - "+TotalTime);

}
}



Output:

Total Time for page load - 4122




To know FAQ's in Interviews on Selenium  ClickHere
To know more on SQL Queries Required For Testers  ClickHere