Automation Using Selenium Webdriver

Friday 11 November 2016

Handle Web Table Dynamically In Selenium WebDriver

Whenever the pagem loads its take the table data dynamically and get the table data.

In this Example am going to take table data for the below table.




Source code :

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;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class testpins {
WebDriver driver = new FirefoxDriver();

@BeforeTest
public void setup() throws Exception {
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.get("http://www.moneycontrol.com/");
}

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

@Test
public void Handle_Dynamic_Webtable() {

// To locate table.
WebElement mytable = driver.findElement(By.xpath("//*[@id='tblrMC']"));
// To locate rows of table.
List<WebElement> rows_table = mytable.findElements(By.tagName("tr"));
// To calculate no of rows In table.
int rows_count = rows_table.size();

// Loop will execute till the last row of table.
for (int row = 0; row < rows_count; row++) {
// To locate columns(cells) of that specific row.
List<WebElement> Columns_row = rows_table.get(row).findElements(
By.tagName("td"));
// To calculate no of columns(cells) In that specific row.
int columns_count = Columns_row.size();
System.out.println("Number of cells In Row " + row + " are "
+ columns_count);

// Loop will execute till the last cell of that specific row.
for (int column = 0; column < columns_count; column++) {
// To retrieve text from that specific cell.
String celtext = Columns_row.get(column).getText();
System.out.println("Cell Value Of row number " + row
+ " and column number " + column + " Is " + celtext);
}
System.out
.println("--------------------------------------------------");
}
}
}

If you run the above code your output look like this,

Number of cells In Row 0 are 0
--------------------------------------------------
Number of cells In Row 1 are 5
Cell Value Of row number 1 and column number 0 Is Gabriel India
Cell Value Of row number 1 and column number 1 Is Nov 5th 2014
Cell Value Of row number 1 and column number 2 Is 83
Cell Value Of row number 1 and column number 3 Is 99.25
Cell Value Of row number 1 and column number 4 Is 19.00
--------------------------------------------------
Number of cells In Row 2 are 5
Cell Value Of row number 2 and column number 0 Is SKF India
Cell Value Of row number 2 and column number 1 Is Oct 8th 2014
Cell Value Of row number 2 and column number 2 Is 1116
Cell Value Of row number 2 and column number 3 Is 1472.50
Cell Value Of row number 2 and column number 4 Is 31.90
--------------------------------------------------
Number of cells In Row 3 are 5
Cell Value Of row number 3 and column number 0 Is Sonata Software
Cell Value Of row number 3 and column number 1 Is Oct 7th 2014
Cell Value Of row number 3 and column number 2 Is 127
Cell Value Of row number 3 and column number 3 Is 153.05
Cell Value Of row number 3 and column number 4 Is 20.37
--------------------------------------------------
Number of cells In Row 4 are 5
Cell Value Of row number 4 and column number 0 Is IFCI
Cell Value Of row number 4 and column number 1 Is Sep 24th 2014
Cell Value Of row number 4 and column number 2 Is 35
Cell Value Of row number 4 and column number 3 Is 43.30
Cell Value Of row number 4 and column number 4 Is 25.51
--------------------------------------------------
Number of cells In Row 5 are 5
Cell Value Of row number 5 and column number 0 Is Minda Industries
Cell Value Of row number 5 and column number 1 Is Sep 15th 2014
Cell Value Of row number 5 and column number 2 Is 434
Cell Value Of row number 5 and column number 3 Is 655.00
Cell Value Of row number 5 and column number 4 Is 51.03
--------------------------------------------------
PASSED: Handle_Dynamic_Webtable

Thursday 10 November 2016

Generate Customized ExcelReports Using TestNG in Selenium

There are many ways to Generate Reports in Selenium. Now I’d like to generate an excel reports. This report will give you the number test cases has been Passed and Failed or Skipped. It’s quite simple to generate this report. All you need to do is just giving a Proper Name and Destination Path (if you’re using the latest jar 4.0.1).
Note: TestNG is required. Without testNG this code won’t work.
There are few steps to be followed to generate Excel Reports. Here I am sharing the snippet.
Download the latest Jar from here ExcelReportGenerator version 4.0.1. Add this Jar into your project BuildPath.
If You’re using Jar 4.0.1 version then you can specify the desired location and File name in the code itself.
Follow the Steps Specified :
Step1: Create a Package ‘ExcelResults’ under your Project (Optional, if you’re using 4.0.1 version).
step2: Create  the test cases which you’d like to automate using TestNg (by using @Test, BeforeTest…….) as Shown.
import org.openqa.selenium.WebDriver;
import org.testng.annotations.Test;
public class Test_98 {
@Test(priority = 1)
public void VerfyingTestCaseID_001() {
System.out.println(“test”);
System.out.println(“this”);
}
@Test(priority = 2)
public void VerfyingTestCaseID_002() {
System.out.println(“test”);
System.out.println(“this”);
}
@Test(priority = 3)
public void VerfyingTestCaseID_003() {
System.out.println(“test”);
System.out.println(“this”);
}
@Test(priority = 4)
public void VerfyingTestCaseID_004() {
System.out.println(“test”);
System.out.println(“this”);
}
@Test(priority = 5)
public void VerfyingTestCaseID_005() {
System.out.println(“test”);
System.out.println(“this”);
Assert.assertEquals(“validText”, “InvalidText”);
}
@Test(priority = 6)
public void VerfyingTestCaseID_006() {
System.out.println(“test”);
System.out.println(“this”);
}
@Test(priority = 7)
public void VerfyingTestCaseID_007() {
System.out.println(“test”);
System.out.println(“this”);
Assert.assertEquals(“validText”, “InvalidText”);
}
@Test(priority = 8)
public void VerfyingTestCaseID_008() {
System.out.println(“test”);
System.out.println(“this”);
}
@Test(priority = 9)
public void VerfyingTestCaseID_009() {
System.out.println(“test”);
System.out.println(“this”);
}
@Test(priority = 10)
public void VerfyingTestCaseID_010() {
System.out.println(“test”);
System.out.println(“this”);
}
@Test(priority = 11)
public void VerfyingTestCaseID_011() {
System.out.println(“test”);
System.out.println(“this”);
Assert.assertTrue(false);
}
@Test(priority = 12)
public void VerfyingTestCaseID_012() {
System.out.println(“test”);
System.out.println(“this”);
Assert.assertTrue(false);
}
@Test(priority = 13)
public void VerfyingTestCaseID_013() {
System.out.println(“test”);
System.out.println(“this”);
}
@Test(priority = 14)
public void VerfyingTestCaseID_014() {
System.out.println(“test”);
System.out.println(“this”);
}
}
Step3 : Create a testng.xml file under your Project as Shown.
<suite name=”Build 2.0.1″>
<test name=”TestReport”>
<classes>
<class name=”Test_98″ />
</classes>
</test>
</suite>
Now Run the testng.xml file.
Step 4 : Now Create a Class ‘ExcelGenerate’  and paste the following code.
import java.io.IOException;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;
public class ExcelGenerate {
public static void main(String[]args) throws ParserConfigurationException, IOException, SAXException
{
ExcelReportGenerator.generateExcelReport(“MyProject.xls”, “D:\\workspace”);
}
}
Step5: Refresh the package ‘ExcelResults’ (If you’re using older version).
Step5 : Results will be generated at your desired path given. (If you’re using 4.0.1 version).
Click here to see the generated report.
Now you see the excelReport Generated. Its so simple huh !!!

*If you see the columns in the excel were disturbed please change the settings or Use the latest Version. I have made this using  ‘Libre’.

Infosys Asked 3 Years Selenium Testing Position

From Java
---------------
1.What is the Difference between final,finally,finalize
2.what is the difference between Call by value and call by referance
3.How to find out the length of the string without using length function
4.How to find out the part of the string from a string
5.difference between throw & throws
6.What is binding(Early and Late binding)
He give Programes
1.Reverse a number
2.1,2,3,4,5,65,76,5,,4,33,4,34,232,3,2323,
find the biggest number among these
simple string programe.
what is exception types of exception
-----------------------------------------
From manual
----------------------------------------
what is the testcase technique
why we write test case.
bug life cycle
what are the different status of bug
what is the different between functional and smoke testing
what is STLC.
he gives a application & tell to write the scenario
some manual testing concepts
-----------------------------
From Selenium
-----------------------------
1.Explain ur roles and responsibilities
2.Explain Automation Life Cycle
3.Which Framework U have Used?
4.Explain Ur Framework
5.What are the things u stored in PageFactory ? Why ?
6.Explain TestNG
7.What are the annotations U have Used ?
8.What is Constructor
9.Where u have used constructor in Selenium?
10.Which model u have followed in ur company?
11.How do you handle dynamics objects in a webpage?
12.How do you handle untrusted SSL certificate in Webdriver?
13.What is the difference between beforemethod and beforetest?
14.How to verify a particular image and its size in a webpage?(Webpage has got many images out of which you have select particular one)
15.What is the use of DesiredCapabilities in Selenium WebDriver?
16.How do you know the Remote m/c details. Like OS, browsers details.
17.How do you find out active elements?


Wednesday 9 November 2016

Compatibility Testing using BrowserStack & Selenium – TestNG

What is Compatibility Testing?
Compatibility testing is a non-functional test to ensure that an application’s compatibility within different environments such various web browsers with various versions, Operating Systems (Windows, Linux, Mac…). In order to pass this test, we also need to check Forward and Backward Compatibility. Here i’m using Browserstack to perform Compatiblity testing.
BrowserStack allows users to make manual and automation testing on different browsers and operation systems.To execute your test scripts using BrowserStack, you need to set parameters of Browsers and Platforms.
There are few steps to be followed to integrate Selenium with BrowserStack.

Step 1 : SignUp for BrowserStack account (Free Trail)
Step 2 : Get your UserName and Access Key (Click on Account at the top and click on ‘Automate‘)
Step 3 : Create your Test scripts using TestNG
Step 4 : Create a TestNG.xml file to run tests in parallel (set platforms and browsers with desired versions).
Step 5 : Execute TestNG.xml.
Step 6 : To view your results, Login and click on ‘Automate‘ link. You can view your project results.
Here I’m providing a sample code. I’m using TestNG to run tests in parallel.
package package1;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.Augmenter;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.testng.Assert;
import org.testng.ITestResult;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
public class BrowserStackTestCase {
private WebDriver driver;
public static final String USERNAME = “YourUserName”;
public static final String AUTOMATE_KEY = “YourAccessKey”;
public static final String URL = “http://&#8221; + USERNAME + “:” + AUTOMATE_KEY
+ “@hub.browserstack.com/wd/hub”;
@BeforeTest
@Parameters(value = { “browser”, “version”, “platform” })
public void setUp(String browser, String version, String platform)
throws Exception {
DesiredCapabilities capability = new DesiredCapabilities();
capability.setCapability(“platform”, platform);
capability.setCapability(“browserName”, browser);
capability.setCapability(“browserVersion”, version);
capability.setCapability(“project”, “MyProject”);
capability.setCapability(“build”, “2.01”);
driver = new RemoteWebDriver(new URL(URL), capability);
}
@Test(priority = 1)
public void testcase001() throws Exception {
driver.get(“http://www.google.com&#8221;);
System.out.println(“Page title : ” + driver.getTitle());
Assert.assertEquals(“Google”, driver.getTitle());
WebElement element = driver.findElement(By.name(“q”));
element.sendKeys(“Merry christmas”);
element.sendKeys(Keys.ENTER);
}
@Test(priority = 2)
public void testcase002() {
driver.get(“http://seleniumhq.org&#8221;);
System.out.println(“Page title : ” + driver.getTitle());
Assert.assertEquals(“Selenium – Web Browser Automation”,
driver.getTitle());
}
@AfterMethod
public void takeScreenShot(ITestResult result) {
if (result.getStatus() == ITestResult.FAILURE) {
driver = new Augmenter().augment(driver);
File srcFile = ((TakesScreenshot) driver)
.getScreenshotAs(OutputType.FILE);
try {
FileUtils.copyFile(srcFile, new File(“D:\\Screenshot”
+ result.getParameters().toString() + “.png”));
} catch (IOException e) {
e.printStackTrace();
}
}
}
@AfterTest
public void tearDown() throws Exception {
driver.quit();
}
}
Now setup your configuration in xml file. Copy the below code.
<suite thread-count=”3″ name=”Suite” parallel=”tests”>
<test name=”FirstTest”>
<parameter name=”browser” value=”firefox” />
<parameter name=”version” value=”38″ />
<parameter name=”platform” value=”Windows” />
<classes>
<class name=”package1.BrowserStackTestCase” />
</classes>
</test>
<test name=”SecondTest”>
<parameter name=”browser” value=”safari” />
<parameter name=”version” value=”6.0″ />
<parameter name=”platform” value=”MAC” />
<classes>
<class name=”package1.BrowserStackTestCase” />
</classes>
</test>
<test name=”ThirdTest”>
<parameter name=”browser” value=”Internet Explorer” />
<parameter name=”version” value=”11″ />
<parameter name=”platform” value=”Windows” />
<classes>
<class name=”package1.BrowserStackTestCase” />
</classes>
</test>
</suite>
That’s it, your Testcases were executed. Just login and click on ‘Automate’ link, you will see your results.
I really thank BrowserStack team for making our job simpler.

Get Attribute Values Using Webdriver

There are cases where you want to get the attributes values and then perform any action.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class GetAttributes {
public WebDriver driver;
private By bySearchButton = By.name(“btnK”);
@BeforeClass
public void setUp() {
driver = new FirefoxDriver();
driver.get(“http://www.google.com/&#8221;);
}
@Test
public void getAttribute_ButtonName() {
WebElement googleSearchBtn = driver.findElement(bySearchButton);
System.out.println(“Name of the button is:- ” +googleSearchBtn.getAttribute(“name”));
}
@Test
public void getAttribute_Id() {
WebElement googleSearchBtn = driver.findElement(bySearchButton);
System.out.println(“Id of the button is:- “+ googleSearchBtn.getAttribute(“id”));
}
@Test
public void getAttribute_class() {
WebElement googleSearchBtn = driver.findElement(bySearchButton);
System.out.println(“Class of the button is:- “+ googleSearchBtn.getAttribute(“class”));
}
@Test
public void getAttribute_InvalidAttribute() {
WebElement googleSearchBtn = driver.findElement(bySearchButton);
//Will return null value as the ‘status’ attribute doesn’t exists
System.out.println(“Invalid Attribute status of the button is:- “+ googleSearchBtn.getAttribute(“status”));
}
@Test
public void getAttribute_ButtonLabel() {
WebElement googleSearchBtn = driver.findElement(bySearchButton);
System.out.println(“Label of the button is:- “+ googleSearchBtn.getAttribute(“aria-label”));
}
@AfterClass
public void tearDown() {
driver.quit();
}
}

How To Write Data in NotePad Using Selenium

Sometimes we have to print some data into Notepad according to our need.So this post helps you to write data into Notepad.
import java.io.BufferedWriter;
import java.io.FileWriter;
public class txt_write
{
public static void main(String[] args) throws Exception
{
FileWriter fr=new FileWriter(“e:\\data.txt”);
BufferedWriter br=new BufferedWriter(fr);
br.write(“This is sample”);
br.newLine();
br.write(“Testing tools”);
br.newLine();
br.close();
}
}

Tuesday 8 November 2016

Test Case Grouping using TestNG ‘Groups’ Annotations

TestNG allows us to group several tests together. You can group certain tests based on what behavior/aspect they are actually testing. You may have a scenario where few tests belong to a certain group(say Regression) and other ones belong to other group(say Sanity) and yet another one belong to other group(say Login). With this approach you may decide to execute only certain group of test and skip other ones(let’s say there was a regression on related code, so we prefer to only execute Sanity related tests).The group test is a new innovative feature in TestNG, it doesn’t exist in Junit framework
Method annotated with @BeforeGroups gets executed only once for a group before any of the test of that group executes. Method annotated with @AfterGroups gets executed only once for a group only after all of the tests of that group finished execution.
Let’s see this with a simple example:
Review a test group example.
  1. checkMail(),deleteMail() and composeMail() are belong to group ‘Sanity’.
  2. checkDrafts(), checkAccountDetails() and checkPromotions() are belong to group ‘Regression’.
  3. If i chose to execute only ‘Sanity’ then Step1 should be  executed.
package samples;
import org.testng.annotations.AfterGroups;
import org.testng.annotations.BeforeGroups;
import org.testng.annotations.Test;
public class TestNG_Groups {
@BeforeGroups(“Login”)
public void login_Account() {
System.out.println(“Account Login”);
}
@Test(groups = “Sanity”)
public void checkMail() {
System.out.println(“Checking Mail in the Inbox”);
}
@Test(groups = “Regression”)
public void checkDrafts() {
System.out.println(“Checking Drafts”);
}
@Test(groups = “Regression”)
public void checkPromotions() {
System.out.println(“Checking Promotions”);
}
@Test(groups = “Regression”)
public void checkAccountDetails() {
System.out.println(“Checking Account Details”);
}
@Test(groups = “Sanity”)
public void composeMail() {
System.out.println(“Send a Mail “);
}
@Test(groups = “Sanity”)
public void deleteMail() {
System.out.println(“Delete a Mail”);
}
@AfterGroups(“Login”)
public void logout_Account() {
System.out.println(“Account Logout”);
}
}
Now create testng.xml file,
<suite name=”Build 2.0.1″>
<test name=”groups Test”>
<classes>
<class name=”samples.TestNG_Groups” />
</classes>
<groups>
<run>
<include name=”Sanity” />
</run>
</groups>
</test>
</suite>


When you run this xml only the Sanity testcases should be executed.We can also use ‘exclude’ to exclude desired testcases.