You are on page 1of 18

//Checkbox

List<WebElement> e = f.findElements(By.xpath("//input[@name='email_to[]']"));
System.out.println(Integer.toString(e.size()));
for(WebElement ela : e )
{
ela.click();
ela.click();

//data to read from excel and sends to login :

public class anno {


public static void main(String[] args) throws BiffException, IOException, InterruptedException {
// TODO Auto-generated method stub
Workbook wb=Workbook.getWorkbook(new File("E:\\excel\\New Microsoft Excel Worksheet.xls"));
Sheet e=wb.getSheet(0);
int totalNoOfRows = e.getRows();
int totalNoOfcols = e.getColumns();
for(int row=1;row<=totalNoOfRows;row++)

for(int col=1;col<=totalNoOfcols;col++)
{
WebDriver d=new FirefoxDriver();
d.manage().window().maximize();
d.get("https://accounts.google.com/");
d.findElement(By.id("Email")).sendKeys(e.getCell(0,row).getContents());
d.findElement(By.id("next")).click();
Thread.sleep(3000);
d.findElement(By.id("Passwd")).sendKeys(e.getCell(1,col).getContents());
d.findElement(By.id("signIn")).click();
d.close();
}
}
}

Zoom browser :

{
WebDriver d;


d=new FirefoxDriver();
d.manage().window().maximize();
d.get("https://accounts.google.com");
d.findElement(By.tagName("html")).sendKeys(Keys.chord(Keys.CONTROL,Keys.ADD));
}

Proxy setting :

Complete file.txt[06-02-2017 11:33:12]


ChromeOptions options = new ChromeOptions();
DesiredCapabilities dc = DesiredCapabilities.chrome();
dc.setCapability("chrome.setProxyByServer", false);
System.setProperty("webdriver.chrome.driver",sChromeDriverPath);
WebDriver driver = new ChromeDriver();

Write Excel :

public class anno {


public static void main(String[] args) throws IOException, RowsExceededException, WriteException {
// TODO Auto-generated method stub
WritableWorkbook wb=Workbook.createWorkbook(new File("D:\\div"));
WritableSheet sh=wb.createSheet("anandh", 0);
Label d=new Label(0,0,"selenium");
Label d1=new Label(1,2,"testing");
sh.addCell(d);
sh.addCell(d1);
wb.write();
wb.close();
}
}

@Data Provider :

@Test(dataProvider = "dp",priority=1)
public void f(String n, String s)

Syntax :

@DataProvider
public Object[][] dp() {
return new Object[][] {
new Object[] { "arun", "1234" },
new Object[] { "test", "4321" },
new Object[] {"user","asasas"},
};

@Parameters :
@Parameters({"user","pass"})
@Test
public void f(String user,String pass)

XML :

Suite file(XML file)-To pass the input for above program


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="Suite1">
<test name="test1">

Complete file.txt[06-02-2017 11:33:12]


<parameter name="myName" value="part"/>
<parameter name="pass" value="part"/>
<classes>
<class name="Param" />
</classes>
</test>
<test name="test2">
<parameter name="Name" value="abc12"/>
<parameter name="pass2" value="123ddff4"/>
<classes>
<class name="Param" />
</classes>
</test>
<test name="test3">
<parameter name="Name3" value="abc1223"/>
<parameter name="pass3" value="123ff4"/>
<classes>
<class name="Param"/>
</classes>
</test>
</suite>

Cross Browser :

@Parameters("browser")
@BeforeTest
public void beforeTest(String browser) throws Exception
{
if(browser.equalsIgnoreCase("firefox"))
{
g=new FirefoxDriver();
}

XML :

<?xml version="1.0" encoding="UTF-8"?>


<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="TestSuite" parallel="tests" >
<test name="ChromeTest">
<parameter name="browser" value="Chrome" />
<classes>
<class name="test.cross">
</class>
</classes>
</test>
<test name="FirefoxTest">
<parameter name="browser" value="Firefox" />
<classes>
<class name="test.cross">
</class>
</classes>
</test>
<test name="IETest">
<parameter name="browser" value="IE" />

Complete file.txt[06-02-2017 11:33:12]


<classes>
<class name="test.cross">
</class>
</classes>
</test>
</suite>

Screen Shots :
File h=((TakesScreenshot)g).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(h, new File("d:\\driver1\\base.png"));

Groups :
@Test(groups={"Smoke"})
@Test(groups={"Regression"})
@Test(groups={"Regression","Smoke"})

XML : <test name="Test">


<groups>
<run>
<exclude name="Smoke" />
<include name="Regression"/>
</run>
</groups>

@Listners :

@Listeners(checking.anno.class)
ITestResult :
@AfterMethod
Public void main(ItestResult result)
{
If(ItestResult.FAILURE==result.getStatus());
{
Utility.CaptureScreeshot(driver.result,getname());
}
Driver.quit();
}

Robot API :

Robot robot = new Robot();


robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);

Alert :

String at=z.switchTo().alert().getText();
System.out.println(at);
if(at.equals("First name Should not contain Special Characters"))
{
System.out.println("pass");
z.switchTo().alert().dismiss();
}

Complete file.txt[06-02-2017 11:33:12]


else
System.out.println("false");

DB Testing :

public class TestDatabase {


@Test
public void TestVerifyDB(){
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
System.out.println("Driver Loaded");
String dblocation= "C:\\Users\\Desktop\\DB\\FacebookDB1.accdb";
Connection con=DriverManager.getConnection("jdbc:odbc:AscentAccess;DBQ="+dblocation);
System.out.println("Connection created");
Statement smt=con.createStatement();
System.out.println("Statement created");
ResultSet rs= smt.executeQuery("Select * from Facebook");
System.out.println("Query Executed");
while(rs.next()){
String uname= rs.getString("username");
String pass= rs.getString("password");
String email= rs.getString("email");
System.out.println("Uname is "+uname+" password is "+pass+" email id is "+email);
}
}
catch (Exception e) {
System.out.println(e.getMessage());
}

Dependens test :

@Test(dependsOnMethods={"testLogin"})

Implicit Wait :

driver.manage().timeouts().implicitlyWait(TimeOut, TimeUnit.SECONDS);

Explicit wait :

Syntax :
WebDriverWait wait = new WebDriverWait(t,30);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("")));
Example :
ElementNotVisibleException
alertIsPresent()
elementSelectionStateToBe()
elementToBeClickable()
elementToBeSelected()
frameToBeAvaliableAndSwitchToIt()
invisibilityOfTheElementLocated()
invisibilityOfElementWithText()
presenceOfAllElementsLocatedBy()

Complete file.txt[06-02-2017 11:33:12]


presenceOfElementLocated()
textToBePresentInElement()
textToBePresentInElementLocated()
textToBePresentInElementValue()
titleIs()
titleContains()
visibilityOf()
visibilityOfAllElements()
visibilityOfAllElementsLocatedBy()
visibilityOfElementLocated()

Assert :

Assert.assertEquals(21, multiply(10, 5));

Xpath :

1. Single attribute :

//tagname[@attribute-name='value1']

Example : //input[@name='log']

2. Double attribute :

//input[@class='input'][@name='log']

3. And & OR

//input[@class='input' and @name='log']

//input[@class='input' OR @name='log']

4. Contains : (Partial contains)

//a[contains(@href,'edit.php')][text()='Posts']

//*[text()='Discussion']//following::a[contains(@href,'edit.php')][text()='Posts']

//a[contains(text(),'Dismiss this message')]

//*[contains(@id,'edit)']

5. Using starts-with method :

//*[starts-with(@id,'edit')]

6. Search by text :

Complete file.txt[06-02-2017 11:33:12]


//*[text()='Howdy,admin']

//a[text()='Please update now']

7. Search by following :

.//*[@id='content-label']/label//following::textarea

.//*[@id='content-label']/label//following::input[2]

8. Search by precedings:

.//*[@id='content-label']/label/preceding::input[2]

Selenium Task :

1. Copy text from Content from one text box to another.

Answer 1: using getText()

public class anno {



public static void main (String[] args ){

WebDriver Driver = new FirefoxDriver();
Driver.manage().window().maximize();
Driver.get("http://www.mycontactform.com/samples.php");
WebElement element =Driver.findElement(By.xpath(".//*[@id='contactForm']/table/tbody/tr[3]/td/label"));
String et = element.getText();
System.out.println(et);

}

Answer 2 : using getAttribute()

public class anno {



public static void main (String[] args ){

WebDriver Driver = new FirefoxDriver();
Driver.manage().window().maximize();
Driver.get("http://www.mycontactform.com/samples.php");
Driver.findElement(By.id("subject")).sendKeys("dinesh.rock");
WebElement element =Driver.findElement(By.id("subject"));
String et=element.getAttribute("value");
System.out.println(et);
Driver.findElement(By.id("email")).sendKeys(et);
}

Complete file.txt[06-02-2017 11:33:12]



}

2. How to get the content from the web table.

Web Tables :

Code for table :-

1. table
2. Th-table heaading
3. Td-Table data
4. Tr-Table row

Answer 1 : To get the all datas from table using xpath(catch the table wii display all the contents) :

public class anno {



public static void main (String[] args ){

WebDriver Driver = new FirefoxDriver();
Driver.manage().window().maximize();
Driver.get("http://toolsqa.com/automation-practice-table/#");
Driver.findElement(By.xpath("//div[@id='content']/table"));
WebElement datas = Driver.findElement(By.xpath("//div[@id='content']/table"));
String tc = datas.getText();
System.out.println(tc);
int total_nodes=dates.size();
for(i=0;i<=totalnodes;i++)
{
String date=dates.get(i).getText();
if(date.equls("31"))
{
date.get(i).click();
break;
}
}

}

Table practise : http://toolsqa.wpengine.com/automation-practice-table/

3. Display all the values in dropdown and select which u want.

Complete file.txt[06-02-2017 11:33:12]


Answer : public class anno {

public static void main (String[] args ){

WebDriver Driver = new FirefoxDriver();
Driver.manage().window().maximize();
Driver.get("http://www.mycontactform.com/samples.php");
//get display all elements in drop down
WebElement datas = Driver.findElement(By.xpath("//select[@id='q3'] [@name='q3']"));
String tc = datas.getText();
System.out.println(tc);

//Select one option in dropdown
Select h =new Select(datas);
h.selectByIndex(2);

//display the selected option
WebElement option = h.getFirstSelectedOption();
System.out.println("Your Selected Option is : "+option.getText());
h.deselectAll();
System.out.println("Nothing Selected");
}

4. Need checkbox content.

5. Get values(Text) from outside file and send to Multiline textbox.

public class anno {



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

WebDriver Driver = new FirefoxDriver();
Driver.manage().window().maximize();
Driver.get("http://www.mycontactform.com/samples.php");
FileReader fr=new FileReader("E:\\New folder\\dinesh.txt");
BufferedReader br= new BufferedReader(fr);
String x=br.readLine();
while ((x=br.readLine()) != null)
{
System.out.println(x +"\n");
Driver.findElement(By.id("q2")).sendKeys(x +"\n");
}


br.close();

}

Complete file.txt[06-02-2017 11:33:12]



}

6. copy content and send to text file.

public class anno {



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

WebDriver Driver = new FirefoxDriver();
Driver.manage().window().maximize();
Driver.get("http://www.mycontactform.com/samples.php");
Driver.findElement(By.id("subject")).sendKeys("dinesh.rock");
WebElement element =Driver.findElement(By.id("subject"));
String et=element.getAttribute("value");
FileWriter fr=new FileWriter("E:\\New folder\\dinesh.txt");
BufferedWriter br= new BufferedWriter(fr);
br.write(et); //Writing In To File.
br.newLine();//To write next string on new line.
br.write(et); //Writing In To File.
br.close();

7. Handling popup window.

public class anno {



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

WebDriver Driver = new FirefoxDriver();
Driver.manage().window().maximize();
Driver.get("http://www.mycontactform.com/samples.php");
String mainwindow=Driver.getWindowHandle();
for (String Child_Window : Driver.getWindowHandles())
{
Driver.switchTo().window(Child_Window);
Driver.findElement(By.id("calendar_month_txt")).click();
Driver.switchTo().window(mainwindow);


}

}}

Multiple windows :

driver.switchTo().window(mainWindowHandle);
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"\t");
driver.switchTo().defaultContent();

Complete file.txt[06-02-2017 11:33:12]


Swithing :

String parent= driver.getWindowHandle();


Set x= driver.getWindowHandles();
Iterator it=x.iterator();
while(it.hasNext()){
String child=it.next();
if(parent.equals(child)){
System.out.println(driver.switchTo().window(child).getTitle());
driver.switchTo().window(parent);
driver.close();
driver.switchTo().window(child);
// Continue your code
}
}
System.out.println(driver.getTitle());

File Handling :


1.InputStream - superclass of all classes representing an input stream (read data from a source).

2.OutputStream - Java application uses an output stream to write data to a destination.

3.FileInputStream -

4.FileOutputStream -

5.SequenceInputStream - Java SequenceInputStream class is used to read data from multiple streams.
It reads data sequentially (one by one).

6.DataInputStream - To read primitive data from the input stream.


Java application generally uses the data output stream to write data that can later be
read by a data input stream.

7.DataOutputStream -To write primitive data from the input stream.


Java application generally uses the data output stream to write data that can later be
read by a data input stream.

8.FileWriter -Java FileWriter class is used to write character-oriented data to a file. It is character-oriented
class which is used for file handling in java.
you don't need to convert string into byte array because it provides method to write string
directly.

9.FileReader - Java FileReader class is used to read data from the file. It returns data in byte format like

Complete file.txt[06-02-2017 11:33:12]


FileInputStream class.

10.BufferedWriter -Java BufferedWriter class is used to provide buffering for Writer instances. It makes the
performance fast. It inherits Writer class.

11.BufferedReader -Java BufferedReader class is used to read the text from a character-based input stream.
It can be used to read data line by line by readLine() method. It makes the performance
fast. It inherits Reader class


1. Code to write and read text in file:

--> Using File Handling - Read content from text file.


--> Write content in to Text File.
--------------------------------------------

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

public class pack{


public static void main(String args[]) throws Exception
{
BufferedWriter out1 = new BufferedWriter(new FileWriter("E:\\File Handling\\practise 1\\dinesh.txt"));
out1.write("string to be copied\n");
out1.close();



BufferedReader in1 = new BufferedReader(new FileReader("E:\\File Handling\\practise 1\\dinesh.txt"));
String str;

while ((str = in1.readLine()) != null) {
System.out.println(str);
}
in1.close();

}}

2. Code to copy text from one file to another file :


-------------------------------------------------------------

Complete file.txt[06-02-2017 11:33:12]


/*
"E:\\New folder\\dinesh.txt"
E:\\New folder (2)"
*/
package mobile;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.OutputStream;

public static void main(String args[]) throws Exception


{
BufferedReader read = new BufferedReader(new FileReader("E:\\File Handling\\practise 1\\mummy.txt"));
BufferedWriter write = new BufferedWriter(new FileWriter("E:\\File Handling\\practise 1\\dinesh.txt"));

String len;

len = read.readLine();

while ((len = read.readLine()) != null)


{

write.write(len+"\n");

}
write.close();
read.close();
}

}

3. Get the files names in the folder :


------------------------------------------

public class pack {


public static void main(String[] args) throws Exception {
File folder = new File("E:\\eclipse_kepler_ide_java");
File[] listOfFiles = folder.listFiles();

for (int i = 0; i < listOfFiles.length; i++) {


if (listOfFiles[i].isFile()) {
System.out.println("File " + listOfFiles[i].getName());
} else if (listOfFiles[i].isDirectory()) {

Complete file.txt[06-02-2017 11:33:12]


System.out.println("Directory " + listOfFiles[i].getName());
}
}}}

4. Read content from multiple files in single folder.


-----------------------------------------------------------------

public class pack{

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


File folder= new File("E:\\File Handling\\practise 1");
File[] listoffiles = folder.listFiles();
for (int i = 0; i < listoffiles.length; i++)
{
BufferedReader reading = new BufferedReader(new FileReader(listoffiles[i]));
String s = "";
while ((s = reading.readLine()) != null)
{

System.out.println(s);
}
reading.close();
}

}
}

5. Get Input from user using Bufferedreader


-----------------------------------------------------------

public class pack {


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

String str1,str2,str3,str4 ="";

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the values :");
str1 =br.readLine()+"\n";
System.out.println("Enter the values :");
str2 =br.readLine()+"\n";
System.out.println("Enter the values :");
str3 =br.readLine()+"\n";
str4=str1+str2+str3;
System.out.println(str4);

}

Complete file.txt[06-02-2017 11:33:12]


Get Input from user using Scanner
--------------------------------------------------

public class pack {


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

String str ="";


Scanner sc = new Scanner(System.in);
System.out.println("enter the values :");
str = sc.nextLine();//sc.nextInt();//Integer.parseInt
System.out.println(str);

}

*BDD

Behaviouur driven development.



Extension of TDD

Tradition approach

Focus on what to test not how to test.

TDD --> business requrements-->System requirements-->Test cases created

Problem : If system requiremets needs more then we cannot continue because Business req is fixed based upon we need
to create.

BDD is controls this by providing some new techniques that -->What to test.

Use plain english and it approcah based upon Exact requirments.

refer cucmber.io link

Cucmber support BDD tool

Complete file.txt[06-02-2017 11:33:12]


Installation :

create project-->name selenium cucmber-->add jars

Gherkins-->separte lang will provide keywords like some meaningfull example -->Given,When ,Then, And etc

Feature : Test Smoke Scenarios of facebook

Scenario : Test Facebook with Valid Crenditals


Given open Firefox and Start application
When i Provide Valid username and password
Then User should be able to login

Project :

New folder --> Features -->Add plugin-->help-->use url -->install-->


Folder -->right click-->new-->file-->myapplication.feature

Feature
Given : preconditions

Specfic test runner :

New --> pkg--> class-->

Maven :

maven 3.3.1

Conti.itergration :

Jenkins--> Automated software to make ci

Most important thinks

*trigger
*Build Steps
*Post Build Steps

Email extension plug ins

Complete file.txt[06-02-2017 11:33:12]


Need to cover extra for scope interview :

1. File handling : refer javaTpoint - Tutorial.

Practise the tasks and understand the file handling methods.

2.String tasks : refer javaTpoint - Tutorial

Practise :

Task 1 : Cut the given strings and save in different file -->part wise storing.

Task 2 : practise using different String methods.

3. Exception Handling (Both selenium and java) and Waits in Selenium.

Selenium :

-->NoSuchElementException

This exception occurs when WebDriver is unable to identify the elements during run time.
Due to wrong selector or selector, which is, not exist.

-->ElementNotVisibleException

This Exception occurs when the element presence is in DOM, it is not visible.
Example:-
Hidden Elements, which has presence in DOM and it, is not visible. Visibility means the height and
width should be greater than zero. Hidden Elements are defined in HTML using of type=”hidden”.

-->NoSuchFrameException

This Exception occurs when the driver is switching to an invalid frame, which is not available.

-->NoAlertPresentException

This Exception occurs when the driver is switching to an invalid Alert, which is not available.

-->NoSuchWindowException

This Exception occurs when the driver is switching to an invalid Window, which is not available.

-->WebDriverException

This Exception occurs when the driver is performing the action after immediately closing the browser.

-->SessionNotFoundException
This Exception occurs when the driver is performing the action after immediately quitting the browser.

-->StaleElementReferenceException

This Exception occurs when the Element belongs to a different frame than the current one. The user has
navigated away to another page.

Complete file.txt[06-02-2017 11:33:12]


-->NullPointerException

When any variable point to null

-->IOException

Whenever we deal with files this checked exception will come.

Waits :

4. Desired Capabilities Detailed Knowledge.

5. OOPS understanding programs.

6.Just understaing Knowledge about resume based questions :

BDD-->Cucumber --> Jenkins Keyword-->Maven Projects.

BDD --> http://www.testingexcellence.com/bdd-guidelines-best-practices/

Cucumber --> Refer the Learn automation.

Jenkins Keyword --> https://www.youtube.com/playlist?list=PLQ9cQ3JqeqU_jniHtZAdvhQU_0vUs8eOC

Maven projects -->http://www.javatpoint.com/maven-tutorial

Complete file.txt[06-02-2017 11:33:12]

You might also like